Using PHP though 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 backup, automatic log tracking and etc.
PHP supports CLI SAPI(Command Line Interface Server API) for executing the 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 the command line, the execution time limit is unlimited by default.
Buffering – implicit_flush is enabled to display output. It also supports output buffering.
CLI SAPI Commands
Following are some of the PHP CLI SAPI command line options.
-i To display command line PHP info.
-v To show version details.
-r To execute PHP script without delimiters -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.
PHP Command Line Examples
Now, let us see some simple example to interact PHP from the command line. These examples deal with PHP where the file name or code is given.
Executing PHP File
Create a PHP program to print an array of colors. The program is,
Save this file as print_array.php and specify the name with PHP command line option -f.
php -f print_array.php
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.