How to set php script to cronjob

Cron is a task scheduler which can execute a task on certain intervals, you can add php script to cron to run it on certain time intervals.
For example you want to delete temporary files after every 14 days, you write a script to delete temporary files and add that script to cron.

How to add php script to cron

There as several ways to add your script to cron. The popular and most easy is using cpanel.

Using Cpanel

Login to cpanel and go to cron jobs, Add new cron and put your php script path as follow in cron command.

/usr/bin/php -q /home/username/public_html/cron.php >/dev/null

Let me epxlain what above command is doing.

/usr/bin/php is php binary path (different in some systems ex: freebsd /usr/local/bin/php, linux: /usr/bin/php, you can find the path in phpinfo or using bash )

/home/username/public_html/cron.php should be your php script absolute path

/dev/null where to save cron output, /dev/null means no output
If you want to save cron output in file for logging purpose use following
For example

/usr/bin/php -q /home/username/public_html/cron.php >/home/username/cron.log

Using SSH

You can set a cron using ssh. Login into your server using ssh and proceed as following

crontab -e

It will open all crons added to your server
You can add your cron like following

00 00 * * * /usr/bin/php /home/username/public_html/cron.php >/dev/null

(00 00 indicates midnight–0 minutes and 0 hours–and the *s mean every day of
every month.)


  mm hh dd mt wd  command

mm minute 0-59
hh hour 0-23
dd day of month 1-31
mt month 1-12
wd day of week 0-7 (Sunday = 0 or 7)
command what you want to run
all numeric values can be replaced by * which means all


#Run cron every minute

* * * * *

#Run cron every five minute

*/5 * * * *

#Run cron every hour
0 * * * * 

#Run cron every 6 hrs
0 */6 * * * 

#Run cron every Friday 8:00
0 8 * * 5 

#Run cron every Sunday Midnight
0 0 * * 0 

That’s it.

Don’t forget to add comments 🙂

One thought on “How to set php script to cronjob

Leave a Reply

Your email address will not be published. Required fields are marked *