run php scripts automatically

How to Run PHP Scripts Automatically

Sometimes you may need to automate PHP scripts for your website or applications. You can easily do this using cron jobs. In this article, we will look at how to run PHP scripts automatically using cron jobs.


How to Run PHP Scripts Automatically

There are two ways to run PHP scripts automatically – using php command or via URL. We will look at both these methods. Let us say you have a PHP script at /var/www/html/test.php whose corresponding URL is http://mydomain.com/test.php


1. Run PHP Script using PHP command

Open terminal to locate php binary.

$ sudo locate php

Mostly, it will be located at /usr/bin/php or /usr/local/bin/php

So the command to run your PHP script from terminal is

$ sudo /usr/bin/php /var/www/html/test.php

We will add the same command in cron jobs. Open it using crontab command

$ sudo crontab -e

Add the following line to create a cron job that runs your script every hour. Please change the cron job frequency (00 * * * *) as per your requirement. Here is the explanation about cron job schedule format.

00 * * * * sudo /usr/bin/php /var/www/html/test.php

Also read : How to Disable Directory Browsing in Apache


2. Run PHP Script Automatically via URL

Since PHP scripts are mostly accessed via URL, every time you access a URL, its corresponding PHP script will be run. So we need to automate the URL access of your PHP script in order to run it automatically. So you can use programs like curl, wget or lynx to open the URL.

For example if your php script’s URL is http://mydomain.com/test.php then the following command can be used to access it via curl utility

$ sudo /usr/bin/curl -O http://mydomain.com/test.php

We will add the above command to cron jobs

$ sudo crontab -e

Add the following line to access your URL every hour. Please change the cron job frequency as per your requirement.

00 * * * * sudo /usr/bin/curl -O http://mydomain.com/test.php

That’s it. As you can see it is very easy to automate PHP scripts. You can run them via php command or by accessing its URL.

Also read : How to Prevent Direct File Download in Apache

Leave a Reply

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