How to Run a PHP File Using crontab

By | September 18, 2008

Yesterday I was asked this question on the phone and it was quite hard to explain in some words. That’s why I decided to create a post that should explain how to do this, as it seems to be a common practice.

When we need to run a PHP file, most often you need to run it by opening a browser window and typing the URL to reach it. As we need to access it using a browser, we should be able to do this via crontab. There are two options to run a PHP file in such a way. Here is the first one:

If lynx is installed on your server (this is most probably done), we may use it as a browser to reach the file. The command will look like this:

10 * * * *  lynx -dump http://yourdomain.com/file.php > output.log

The command above will catch the output of your PHP file to output.log. It works like a browser visit and it’s a common solution. You may not catch the output or catch it to /dev.null – it’s your choice.

The second solution is to use wget. wget acts in a similar way: I’ll show you just the command:

10 * * * *  wget http://yourdomain.com/file.php > output.log

This command will also access your PHP file via HTTP.

Sometimes you need to run a PHP file via CLI (command line). For example, you have a file with pcntl functions used and you can run it via command like only. How can we do that using crontab?

We need to know the path to your server’s PHP installation. Most probably your PHP executable is located at /usr/local/bin/php, but this really depends on server OS and PHP installation. You should ask your hosting provider or server administrator about the PHP path. The next thing we need to know is the full path to the PHP file we need to run. This seems to be much easier: just run getcwd() in any script located at the same level as the file you’d like to run and you will find where your file is located. For example, the file that will determine the path will look:

<?
echo getcwd();
?>

Now we need to add these values to your crontab line.

10 * * * *  /path/to/php /path/to/your/php/file/file.php

Most probably it will look like

10 * * * * /usr/local/bin/php /home/username/domains/userdomain.com/userdir/file.php

You can also save the output of this command to a file by adding > output.log

These three methods are available for you. You need just to choose which one is better for you.

4 thoughts on “How to Run a PHP File Using crontab

  1. luke

    cool. i got it work out.
    thanks for your useful tips.

  2. Nate

    Fantastic!
    I was getting fairly frustrated with a lack of documentation on cronjobs, but this walkthrough worked like a charm! Many thanks for helping me keep my hair!

  3. Sekar

    anyone can understand easily and have in mind forever.. thanks dude!!

Comments are closed.