Clever website slogan
Home > Tech > PHP

PHP Command Line Usage

There are a number of ways to execute PHP code from the command line. You can tell PHP to execute a certain file, pass PHP code directly on the command line or provide PHP the code to execute via standard input (stdin).

php my_script.php php -r 'echo "Hello World!\n";' some_application | some_filter | php | sort -u > final_output.txt

Interactive Shell

PHP provides an interactive shell with the -a option. With the interactive shell you can type PHP code and have it executed directly.

$ php -a Interactive shell
php > echo 2+4;
6 php > function AddTwo($n) { php { return $n + 2; php { } php > var_dump(AddTwo(4)); int(6)
php >

PHP Shell Scripts

PHP scripts may also be executed from the command line instead of by a web server (on Ubuntu you may need to install the php5-cli package). The following example asks for user input:

#!/usr/bin/php <?php echo "Are you sure you want to do this? Type 'yes' to continue: "; $handle = fopen ("php://stdin","r"); $line = fgets($handle); if(trim($line) != 'yes') { echo "ABORTING!\n"; exit; } echo "\n"; echo "Thank you, continuing...\n"; ?>

If you want to set windows file associations for php scripts from the command line use:
ASSOC .phs=PHPScript
FTPYE PHPScript=[path to]\php.exe -f "%1" -- %*
optional set PATHEXT=.phs;%PATHEXT%

Also see PHP-GTK, among others, for creating PHP based desktop applications.

Input/Output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

STDIN An already opened stream to stdin. This saves opening it with <?php
$stdin = fopen('php://stdin', 'r');
If you want to read single line from stdin, you can use <?php
$line = trim(fgets(STDIN)); // reads one line from STDIN
fscanf(STDIN, "%d\n", $number); // reads number from STDIN
STDOUT An already opened stream to stdout. This saves opening it with <?php
$stdout = fopen('php://stdout', 'w');
STDERR An already opened stream to stderr. This saves opening it with <?php
$stderr = fopen('php://stderr', 'w');

Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

php -r 'fwrite(STDERR, "stderr\n");'

You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.