Creating a cron job in cPanel to run PHP script

A cron job, once created, will run repeatedly as specified, to execute the given command on the hosting server. Creating a cron job in cPanel is very simple.

Since you ended up here, I assume you are trying to run a PHP script on regular interval to do some task, for example: backing up a mysql datebase on the hosting server.

What is a cron job? Why do you need it?

PHP is a server side scripting language that dynamically generates web pages as and when requested. As underlined to highlight, PHP scripts are executed only when requested and cannot run automatically or periodically by itself. A Cron is a process running on the web server 24×7. By creating a cron job you are telling your web server to execute the given command automatically, again and again and in the once per specified time interval. This becomes handy in many situations. For example clearing temp memory on the server once in a day, sending automated newsletters once in a month, deleting log files once in a year, etc.

Creating a cron job in cPanel

1. Login to cPanel. Click “Cron Jobs” under Advanced tab.

Creating cron job in cpanel

2. Enter an email ID. When your cron runs successfully, you will receive a notification email to this ID.

Creating a cron job in cPanel

3. Enter how often you want to run this cron job. You can also select one from the “Common Settings” drop down box. Other text boxes will automatically be filled.  I am selecting “Once an Hour”.

Setting up how often a cron job should run

4. Enter

/usr/bin/php -q /home/codezag/public_html/run-every-hour.php

where

/usr/bin/php is path to your PHP binary. You can ask your hosting provider is this path or run whereis php shell command to get the path to php binary on your hosting server.

ALSO READ  Hosting website and emails on different servers

-q command prevents sending HTTP headers while running the cron command.

/home/codezag/public_html/run-every-hour.php is the absolute path to the PHP script to be executed. Click “Add New Cron Job”.

 

If your cron job did not run on the specified time (on top of every hour as in our example) please check whether your server timezone is same as your  actual timezone. In such cases, your cron will run properly but on top of every hour of your server timezone which will be different from that of your’s.

If you have any issues in setting up a cron job in cPanel, please comment below.

Leave a Reply