Using PHP through the command line is possible and we will see 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 back up, automatic log tracking and etc.
PHP supports CLI SAPI(Command Line Interface Server API) for executing the script from the command line. This SAPI will differ from other interfaces based on the IO practices, configuration defaults, buffering and more. For example,
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 the syntax of the given file. |
-w | To strip comments, white spaces from given file and print. |
-a | To run in the interactive shell environment. |
Note: Try with –h to know about more command options in CLI SAPI.
Now, let us see some simple examples to interact with PHP from the command line. These examples deal with PHP where the file name or code is given.
Create a PHP program to print an 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 the PHP command-line option -f.
>php -f print_array.php
This command will execute php_array.php and print the result as,
We are going to execute PHP code in the command prompt. In this example, the PHP echo statement is executed by using the command-line option -r.