UltraMega Blog

PHP in the Shell

PHP may be most commonly used within a web server to produce web pages, but it is a powerful scripting engine by itself. PHP is an amazingly useful multipurpose tool when used from the command line. This post will show you how to use the PHP Command Line Interface (CLI). Some of the information here is Linux specific, but there are equivalents for Windows.

Accessing the PHP CLI

Obviously the first thing you need to know is how to run PHP from the command line. There are a number of ways to do this, and one way that I prefer.

The method I find easiest is to write your script as a shell script. This basically means taking a regular PHP script and adding a line to the beginning declaring the php binary to interpret the script. Here's an example:

< ?php
echo 'Hello World';

Assuming the file name 'test.php' you would make it executable with chmod +x test.php and run it simply with ./test.php. Note that the file does not need to end with .php to function.

Other options for accessing the PHP CLI are to pass scripts or code to php as parameters, pass code to php through standard input, or enter code manually in interactive mode.

File as parameter:

$ php test.php

Code as parameter:

$ php -r "echo 'Hello World';"

Code through standard input (generate_php_code outputs code):

$ generate_php_code | php

Interactive mode:

$ php -a
Interactive shell
php > echo 'Hello World';
Hello World
php >

Accessing the Command Line From PHP

This tutorial will explain the different methods of accessing the system command line from a PHP script. Being able to run external programs can come in handy, and fortunately there are multiple functions that will do this. We will explain the differences betweeen these so you can choose the best one for your purpose. The functions covered are exec(), system(), passthru(), and shell_exec(), as well as escapeshellcmd() and escapeshellarg(). See the manual for more information on these functions.