What is PHP CLI, and how to run scripts from the command line?

PHP CLI (Command-Line Interface) is a feature of PHP that allows you to run PHP scripts from the command line or terminal. Unlike traditional web-based PHP scripts that run in a web server environment, PHP CLI scripts are executed directly on the server or local machine, making them suitable for a wide range of tasks, including automation, scripting, and system administration.


To run PHP scripts from the command line, follow these steps:


  1. Install PHP: Ensure that PHP is installed on your system. You can check if PHP is installed by opening a terminal window and running the following command:
php -v

If PHP is not installed, you can download it from the official PHP website ( or use a package manager like `apt` (for Ubuntu) or `brew` (for macOS).


  1. Create a PHP Script: Write your PHP script using a text editor of your choice. Save it with a `.php` extension. For example, you can create a file named `myscript.php`.


  1. Run the PHP Script: Open your terminal, navigate to the directory containing your PHP script, and run the script using the `php` command:
php myscript.php


  1. Command-Line Arguments: You can pass command-line arguments to your PHP script by adding them after the script name. PHP provides access to command-line arguments through the `$argv` array:
// myscript.php
echo "Hello, " . $argv[1] . "!\n";

Run the script with an argument:

php myscript.php John

This will output: “Hello, John!”


  1. STDOUT and STDERR: PHP CLI allows you to send output to the standard output (STDOUT) or standard error (STDERR) streams. You can use functions like `echo` or `print` to display output.


  1. Script Execution: PHP CLI scripts can perform various tasks, such as file manipulation, data processing, and interacting with databases, making them versatile tools for automating tasks and running server-side scripts without the need for a web server.


PHP CLI is a valuable tool for developers and system administrators, as it provides a convenient way to execute PHP scripts outside of a web server context, making it suitable for a wide range of tasks and automation processes.

Previously at
Flag Argentina
time icon
Full Stack Engineer with extensive experience in PHP development. Over 11 years of experience working with PHP, creating innovative solutions for various web applications and platforms.