What it is
The PHP Command Line Interface (CLI) allows you to execute PHP scripts and interact with the PHP interpreter directly from your terminal, useful for automation, scripting, and running background tasks.
Installation
Linux (Debian/Ubuntu)
sudo apt update
sudo apt install php-cli
Linux (Fedora/CentOS/RHEL)
sudo dnf install php-cli
# or
sudo yum install php-cli
macOS (using Homebrew)
brew install php
Windows (using official installer or package manager)
Download the latest PHP for Windows from the official PHP website and ensure the php.exe directory is added to your system’s PATH environment variable. Alternatively, use a package manager like Chocolatey:
choco install php
Core Concepts
SAPI (Server API)
The CLI is one of the SAPIs for PHP. When you run php script.php, you’re using the CLI SAPI, which differs from the web SAPI (like Apache’s mod_php or FPM) in terms of available environment variables, execution time limits, and input/output handling.
Exit Codes
PHP scripts can return an exit code to the shell, indicating success (0) or failure (non-zero). You can explicitly set this using exit(0); for success or exit(1); for failure.
Commands / Usage
Running Scripts
Execute a single PHP file:
php my_script.php
Runs the my_script.php file.
Execute a file with arguments:
php process_data.php --input data.csv --output results.json
Runs process_data.php and passes --input data.csv and --output results.json as command-line arguments.
Execute inline PHP code:
php -r 'echo "Hello, CLI!\n";'
Executes the given PHP code directly without needing a file.
Execute a file from a different directory:
php /path/to/your/scripts/cron_job.php
Runs a PHP script located in a specified directory.
Interactive Shell
Start the interactive PHP shell (REPL):
php -a
Opens an interactive shell where you can type and execute PHP code line by line. Type exit or press Ctrl+C to quit.
Configuration and Information
Display PHP version:
php -v
Shows the installed PHP version and build information.
Display PHP configuration:
php -i
Outputs detailed information about the current PHP configuration, similar to phpinfo().
Display specific configuration directive:
php -i | grep "memory_limit"
Filters the configuration output to show only the line containing memory_limit.
Display configuration file path:
php --ini
Lists the loaded configuration file (php.ini) path and scanned directory.
Script Execution Options
Specify a different PHP configuration file:
php -c /etc/php/7.4/cli/custom.ini my_script.php
Uses the specified custom.ini file instead of the default php.ini.
Disable short open tags:
php -y my_script.php
Disables short open tags (<?) for the current execution. (Note: -y is for disabling short tags, -z is for enabling them).
Enable short open tags:
php -z my_script.php
Enables short open tags (<?) for the current execution.
Set a specific include path:
php -i /var/www/includes my_script.php
Sets the include path for include and require statements for this execution.
Run script with a specific memory limit:
php -d memory_limit=256M my_script.php
Sets the memory_limit to 256MB for the execution of my_script.php.
Run script with a specific execution time limit:
php -d max_execution_time=300 my_script.php
Sets the max_execution_time to 300 seconds (5 minutes) for my_script.php.
Run script with error reporting enabled:
php -d error_reporting=E_ALL my_script.php
Sets the error_reporting level to display all errors.
Run script with display errors enabled:
php -d display_errors=1 my_script.php
Enables display_errors for the execution, useful for debugging.
Input and Output
Read from standard input:
echo "<?php echo 'Hello from stdin!';\n" | php
Pipes content to the PHP interpreter, which executes it.
Specify the script to execute (alternative to file argument):
php -f my_script.php
Explicitly specifies my_script.php as the file to execute.
Extensions
Manually enable an extension:
php -d extension=redis.so my_script.php
Loads the redis.so extension for the current script execution. This assumes the extension is compiled or available in a location PHP can find.
Common Patterns
Running a scheduled task (cron job):
# Example crontab entry to run a daily cleanup script at 2 AM
0 2 * * * /usr/bin/php /var/www/html/cron/daily_cleanup.php >> /var/log/cron.log 2>&1
This executes a PHP script at a specific time, redirecting output and errors to a log file.
Executing a PHP script and capturing its output:
RESULT=$(php process_users.php --type active)
echo "Active users processed: $RESULT"
Runs a PHP script, stores its standard output in the RESULT shell variable, and then uses it.
Processing CSV data from standard input:
cat input.csv | php csv_processor.php
Pipes the content of input.csv to csv_processor.php, which can then read from STDIN using fopen('php://stdin', 'r').
Running a simple web server for local development:
php -S localhost:8000
Starts a built-in web server on localhost port 8000. This is useful for quick testing of web applications without a full server setup.
Running a web server on a specific directory:
cd public_html
php -S localhost:8000
Starts the built-in web server, serving files from the public_html directory.
Executing multiple commands sequentially:
php setup.php && php run_tests.php
Runs setup.php, and if it exits successfully (exit code 0), then runs run_tests.php.
Executing a command only if the previous one fails:
php deploy.php || echo "Deployment failed!"
Runs deploy.php, and if it fails (non-zero exit code), then prints "Deployment failed!".
Passing environment variables to a script:
export DATABASE_URL="mysql://user:pass@host/db"
php migrate.php
Sets an environment variable DATABASE_URL that can be accessed within migrate.php using getenv('DATABASE_URL').
Gotchas
memory_limit and max_execution_time: By default, CLI has a memory_limit of -1 (unlimited) and max_execution_time of 0 (unlimited), unlike the web SAPI. This can be overridden using -d or php.ini.
$_SERVER['REQUEST_METHOD'] and related variables: Many web-specific $_SERVER variables (like REQUEST_METHOD, HTTP_HOST, REMOTE_ADDR) are not set when running via CLI. You should not rely on them in CLI scripts.
Relative paths: Relative paths in CLI scripts are resolved based on the directory from which the php command is executed, not necessarily the directory where the script resides. Use __DIR__ to get the script’s directory reliably: require __DIR__ . '/../vendor/autoload.php';.
Short open tags (<?): While enabled by default in older PHP versions, it’s good practice to always use <?php for maximum compatibility and clarity, especially in CLI scripts that might be run on different environments. The -z and -y flags can control this behavior.
php.ini loading: The CLI SAPI looks for php.ini in different locations than the web SAPI. Use php --ini to see which php.ini file is being loaded. You can specify a custom one with -c.
Permissions: Ensure the PHP executable has execute permissions and that the script file is readable by the user running the command.