PHP CLI

30 November -0001
by: Justin Klein Keane
May 25, 2006

The PHP CLI (Command Line Interface) has been a standard part of PHP since version 4.3.0. PHP CLI allows you to write scripts that perform at a shell level rather than having to be interpreted by a web browser.

One of the main advantages of PHP CLI is that you can leverage existing classes and functions.

Many argue that PHP CLI is trying to make PHP all things to all people and mimic functionality of Perl. While PHP CLI is admittedly weaker than Perl, the fact that a new language is not required in order to write scripts makes it a viable alternative.

PHP CLI programs can be automated using CRON or any other automating tools.

The only thing that differentiates a PHP CLI program from a regular PHP script is the first line begins:

#!/usr/bin
 

Or with an appropriate pointer to the PHP CLI executable (on a Windows system this might be #!C:\php)

The PHP CLI has functions similar to Perl for collecting user input, command line options and other external information. For instance:

#!/usr/bin
<?php
	$user_name = trim(fgets(STDIN));
	echo 'hello ' . $user_name . "\n";
?>

Would ask for the user name and respond with a string containing the value provided by the user.

http://us2.php.net/features.commandline provides a more complete overview of CLI functionality.

Although it is easy to write procedural PHP using the CLI, it is also possible to write object oriented PHP CLI code and even to utilize existing libraries (such as PEAR).