Running PHP from the comand line (CLI)

By reeset / On / In Uncategorized

I occasionally have occasion to build small projects (web and command line) to do various things.  A lot of times, these projects could be done in things like Rails or another framework, but honestly, I don’t need that much overhead so I fall back to using PHP or PERL.  Between the two, I prefer working with PHP and setting it up to work as a traditional shell script.  It’s fairly easy, and here’s how.

First, you need to make sure that PHP CLI is installed.  You can do this by checking the version.
reeset@enyo home]$ php -v
PHP 5.3.3 (cli) (built: Jul  3 2012 16:53:21)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

Essentially, you are looking for the text, cli in the version string.  If you have it, you are good to go.  If not, you’ll have to hunt down and install it using apt-get for example. 

Once you are set, you just need to hunt down the full path to the php binary.  I find that it often can be found at /usr/bin/php.  You’ll want to confirm that path because you’ll need it later.

Because I want to turn this into more of an executable script, I don’t want to have to run the script using the php command line.  So, I’m going to add a shebang to the first line of the script file.  This was new for me – I hadn’t realized that this was possible in PHP until I was looking through the manual, and for CLI scripts, I definitely prefer this method. 
Example script:
      echo “PHP CLI script \n”;

The shebang allows the script to be run without refererncing the PHP executable in the command line.  Now, all you need to do is make the file executable. 
chmod +x yourphpfile.php

With the file set as executable, you can now run the script like any other shell script, i.e.; ./yourphpfile.php