Command Line PHP

by Vincy. Last modified on July 9th, 2022.

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,

  • IO practices – it will not support the 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.

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.

PHP Command Line Examples

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.

Executing PHP File

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

$colors = array(

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,


Executing PHP Code

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.


Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page