Running PHP scripts as shell scripts
Posted February 2nd, 2009 in PHP
As well as running PHP scripts via a web server such as Apache, you can also run PHP scripts from the command line (it's also possible to write GUI apps with PHP using PHP-GTK, but I'll maybe look at that another time). This post looks at the two ways you can run a PHP script from a *nix based computer (Linux, UNIX, BSD, OSX) and the single way you can do it from Windows.
Using a shebang
UNIX shell scripts are set as executable and the first line in the file contains a "shebang" line which shows the path to the executable which will parse the script.
If your distro's PHP binary is at e.g. /usr/bin/php you would add this to the first line of your script:
and then have your PHP script under it.
To run a "hello world script" you'd do this:
#!/usr/bin/php <?php echo "hello world\n";
The script then needs to be marked as executable. To set it so it can be run as anyone do this:
chmod 0755 /path/to/script.php
To make it so only you can run it (and so no one else can even read it) do this:
chmod 0700 /path/to/script.php
Read the chmod manpage for more details about file permissions if you don't know about them. I have a copy of the chmod manpage here.
Calling the PHP binary, passing the script filename
To avoid permission issues, or to run the PHP script from the command line on Windows (the above method does not work on Windows unless run via cygwin), you need to execute the PHP binary passing the script filename as the parameter.
If you are in the same directory as the script, the script is named e.g. myscript.php, and the PHP binary is at /usr/bin/php you would do this to run it:
If the PHP binary is in your executable path (it usually will be on most Linux distros) then you should just need to run "php" and then the script:
If you're running it from cron it's always a good idea to put the full path to both:
When using this method you don't need to have the shebang line at the top of the script.
An example of doing this on Windows:
It's easy to run a PHP script from the command line, which is useful for batch processing or database cleanup for your website. Combined with automatic processing via the cron system and you have a powerful tool at your disposal if you are a PHP programmer and/or your website is programmed in PHP.