I already knew how to run PHP scripts from the command line (CLI), although I never really used it. What was new to me was that there are 2 ways of doing this. The first one is by using the php command and the second, and new for me, is by adding a shebang on the first line of your script.
Why would you want to use PHP CLI ? Well you don’t have to learn another programming language like perl or bash to make shell scripts, you can run cron jobs in PHP and you can reuse code from a website for example in your shell script.
Before you read any further, the examples below will work for linux and Mac OS X, but not for Windows. I used Ubuntu 8.04 server and Mac OS X 10.5.6.
First you’ll have to make sure that PHP CLI is installed.
johan@ubusrv:~$ php -v PHP 5.2.4-2ubuntu5.3 with Suhosin-Patch 0.9.6.2 (cli) (built: Jul 23 2008 06:44:49) Copyright (c) 1997-2007 The PHP Group Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
If you see ‘cli’ somewhere on the first line, you are ready to go, otherwise you will have to install it first. For example on Ubuntu:
johan@ubusrv:~$ sudo apt-get install php5-cli
It it also useful to know the full path to the PHP binary on your computer. There are several ways of finding out. For Ubuntu and Mac OS X the path is ‘/usr/bin/php’.
johan@ubusrv:~$ which php /usr/bin/php johan@ubusrv:~/cli$ whereis php php: /usr/bin/php /usr/share/php /usr/share/man/man1/php.1.gz johan@ubusrv:~/cli$ type -a php php is /usr/bin/php
For the first method we’ll use the following script:
<?php echo "First PHP CLI script\n"; echo exec('ls -l\n') . "\n"; ?>
You can either execute it by using the php command or by using the full path of the php binary. In this case it is not necessary to make the file exectuable.
johan@ubusrv:~/cli$ php firstcli.php First PHP CLI script -rw-r--r-- 1 1000 1000 71 2009-01-01 19:39 firstcli.php johan@ubusrv:~/cli$ /usr/bin/php firstcli.php First PHP CLI script -rw-r--r-- 1 1000 1000 71 2009-01-01 19:39 firstcli.php
For the second method we’ll add a shebang to the first line of the script:
#!/usr/bin/php -q <?php echo "First PHP CLI script\n"; echo exec('ls -l\n') . "\n"; ?>
I have added the ‘-q’ in the shebang, because you will find a lot of examples like this, but you don’t need it. According to the PHP Manual CLI is started up in quiet mode by default, though the -q and –no-header switches are kept for compatibility so that you can use older CGI scripts.
After you’ve made the file executable, you can now run it like any other shell script.
johan@ubusrv:~/cli$ chmod +x firstcli.php johan@ubusrv:~/cli$ ./firstcli.php First PHP CLI script -rwxr-xr-x 1 1000 1000 89 2009-01-01 19:56 firstcli.php johan@ubusrv:~/cli$ /home/johan/cli/firstcli.php First PHP CLI script -rwxr-xr-x 1 1000 1000 89 2009-01-01 19:56 firstcli.php
|My software never has bugs, it just develops random features|