Cron is a utility that allows you to schedule your task so that later it can be run automatically. It is basically a program that runs at the back of the process and can be scheduled (time-based) through commands or cPanel on web hosts. These commands are nothing but the jobs or tasks that are called “Cron Jobs”. Cron is also available with the Unix-like operating systems such as Linux, Mac, FreeBSD, etc.
Running PHP scripts from Cron jobs.
Running PHP scripts from a cron job using a command-line program such as curl or wget is a common way.
For example : a cron job runs a command like
where, curl accesses the web page, which then runs the PHP script.
However, you can also run the script directly by using the PHP command-line interpreter. This is also an effective and faster method to run PHP scripts on our website from cron jobs.
Let’s see a command that shows how to run a script using the PHP command-line interpreter :
php -q /home/username/public_html/script.php
In this above example, the PHP command-line interpreter runs the script.php file.
The -q option is responsible to enable quiet mode which prevents HTTP headers from being displayed.
Your PHP script can run correctly only when it is called from a specific directory that depends on the code in your PHP script.
For example, if the script has to use relative paths to include files, then it will only run when it is called from the correct directory. A command for how to call a PHP script from a specific directory is :
cd /home/username/public_html/; php -q script.php
For the special configuration options in your script, you can use a custom php.ini.file like the example shown below :
php -c /home/username/php.ini /home/username/public_html/script.php
Here, -c option allows you to call a PHP script using a custom php.ini file.
This is all about how you can PHP script from cron jobs.