Command Line PHP

Using PHP though command line is possible and we will see about how to do it in this tutorial. Generally, PHP is used for creating web-based applications. There are occasions where PHP script can be used apart from regular web applications such as, automatic mail sending, cron job for getting backup, automatic log tracking and etc.

PHP supports CLI SAPI(Command Line Interface Server API) for executing script from command line. This SAPI will differ from other interfaces based on the IO practices, configuration defaults, buffering and more. For example,

  • IO practices – it will not support PHP request method (GET, POST). Instead it uses IO streams.
  • Command line execution time -  In command line the execution time limit is unlimited by default.
  • Buffering – implicit_flush is enabled to display output. It also supports output buffering.

php-command-line

CLI SAPI Commands

Following are some of the PHP CLI SAPI command line options.

Command Description
-i To display command line PHP info.
-v To show version details.
-r To execute PHP script without delimiters <?php…?>
-f To execute PHP file.
-l To check syntax of the given file.
-w To strip comments, white spaces from given file and print.
-a To run in interactive shell environment.

Note: Try with –h to know about more command options in CLI SAPI.

PHP Command Line Examples

Now, let us see some simple example to interact PHP from command line. These examples deals with PHP where the file name or code is given.

Executing PHP File

Create a PHP program to print array of colors. The program is,

<?php
$colors = array("Red","Green","Blue");
print_r($colors);
?>

Save this file as print_array.php and specify the name with PHP command line option -f.

>php -f print_array.php

This command will execute php_array.php and print the result as,

2014-08-25_19-10-52

Executing PHP Code

We are going to execute PHP code in command prompt. In this example, PHP echo statement is executed by using command line option -r.

2014-08-25_19-14-47

This PHP code tutorial was published on August 25, 2014.

↑ Back to Top