php from the Command Line

Using php at the command line isn’t an exact science in regard to which scripts that run in a web page will function from the shell. However, if you are automating many tasks, such as how you would go about with a shell script, then php is a nice alternative to other languages. To get started, let’s look at the version of php that we’re running. A quick way to test this is type the following from the command line.
php -v
This should result in something like the following message, which includes the version of PHP you are running and the current date:
PHP 5.3.0 (cli) (built: Jul 19 2009 00:34:29) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
In its most basic form, the CLI interface can be used just like any PHP script. Create a sample script similar to the following, which we will save as test.php:
<?php print “This is a test.”; ?>
Next we will make this script executable by using the chmod command:
chmod +x test.php
You can execute this script by entering the following command at a shell prompt provided that you have executable permissions to the script:
php test.php
You can avoid calling the php command first on UNIX-based systems by placing a reference to the PHP program right at the start of the script. This tells the shell which program should be used to execute the script. Here’s an example:
#!/usr/local/bin/php <?php print “Hello World!”; ?>