Header Code

How to run a PHP script as Cron job from SSH (Linux shell) 12Nov, 2010

You can run a PHP script on cron by setting up a crontab

For this, first login to your shell using an SSH client such as PuTTY. And on the command line, type the following command (here # means the shell prompt):
# crontab -e

That will put you in the Vi editor editing your crontab. First press “i” to begin inserting, then type out your cron line following the format below for each line, then press the “escape” key on your keyboard to get out of insert mode, and then type “:wq” and press “enter” to save it.

The form of a crontab file is: minute hour day month weekday command
For example: 42 4 1 * * /usr/bin/php /full/path/to/myscript.php

The first part (those first five figures) is where the schedule is set. Those numbers and asterisks represent units of time. For the example above, this part: 42 4 2 * * can be read as:
42: The 42nd minute
4: Of the 4th hour
2: of the 2nd day
*: of any month
*: on any day of the week

Or, more briefly – the second day of every month at 4:42 am

If you want to run a script at every minute then simply use this: * * * * *

The second part to know is where the PHP interpreter on your server is run from; to find that path use this command: # which php which would return the directory such as this: /usr/bin/php

The third part is the full path on the server where your script lies.

A proper crontab might look like this:
MAILTO=yourname@yourdomain.com
42 4 1 * * /usr/bin/php /full/path/to/myscript.php

If you do not want to receive the cron output via email then use this:
42 4 1 * * /usr/bin/php -q /full/path/to/myscript.php

The -q flag suppresses HTTP header output. As long as your script itself does not send anything to stdout, -q will prevent cron from sending you an email every time the script runs.

To view your crontab file, type:
# crontab -l

To remove your crontab, type:
# crontab -r

If your PHP scripts do not have executable permissions, 644 or -rw-r–r– for example, then as part of the command portion of the cron line, you must specify the php interpreter and pass it the filename of the PHP script (including full path to the script from your home directory) that you want executed. If your PHP scripts do have executable permissions like 755 or -rwxr-xr-x and they have one of the PHP filename extensions, then you do not need to specify the php interpreter in the command portion of your cron line.

When you explicitly specify the php interpreter /usr/bin/php your scripts need not have filenames ending in .php .phtml .php3 .php4. Conversely, if your script filenames do not end in one of those PHP extensions, then you must explicitly use the php interpreter in the command portion of your cron as above.

Note that changes to your crontab may take a few minutes to synchronize with the main cron server.

Posted by: Aman Brar / In: Cron, SSH and Tagged , , ,
Cam