create a cronjob to run PHP script

6,851

The "problem" is typically PHP is intended to run as module in a webserver. You may need to install the commandline version of php before you can run php scripts from the commandline:

apt-get install php5-cli

/usr/bin/php is default location for the php binary to be placed, but if you for instance compile php from source it may be somewhere else.

Typically PHP scripts aren't formatted as shell scripts, so you need to tell cron which interpreter should be used to execute the php script; that's the reason to use the commandline /usr/bin/php /var/www/pgrouting/workshop/web/php/calculation.php.

You could format you script with the shebang and make it executable (chmod +x script.php) and then you can call it directly from the commandline, without specifying php as the interpreter ( i.e. ./script.php) :

#!/usr/bin/php
<?php
  print "Hello world!\n" ;
?>
Share:
6,851

Related videos on Youtube

smk
Author by

smk

Updated on September 18, 2022

Comments

  • smk
    smk over 1 year

    I've created a cronjob in Xubuntu to run a PHP script in every 5 minutes. I did it as follows.

    I entered the following command:

    $ crontab -e
    

    Then entered the following:

    */5 * * * * /usr/bin/php /var/www/pgrouting/workshop/web/php/calculation.php
    

    I don't understand what is use of /usr/bin/php and there is no such a file in bin directory, but the PHP script won't run?

    • slm
      slm over 10 years
      Is php installed? type -a php. What Linux distro are you on?
    • smk
      smk over 10 years
      I typed -a php in terminal command was not found.Should i need to install php? I'm using Ubuntu LTS 12.04
    • slm
      slm over 10 years
      Yes you need to install it. sudo apt-get install php
    • smk
      smk over 10 years
      php has installed but no change
    • terdon
      terdon over 10 years
      @slm meant you should run type -a php, the type is a command, he did not mean to type -a php. You need the PHP interpreter (called php and usually found at /usr/bin/php) to tun PHP programs. If you don't have one, you can't run them, cron has nothing to do with it.
  • slm
    slm over 10 years
    What if he doesn't have a web server there to run this?
  • Hải Phạm Lê
    Hải Phạm Lê over 10 years
    I assumed that he has this set up. Sorry for my prejudice.
  • slm
    slm over 10 years
    Just prefix your answer stating that is your assumption. I don't think it's a bad one, but since he showed the example as calling php I would assume that he wants to use it as a scripting lang. and not necessarily from a web server.