The PHP command line interface (CLI) is a powerful tool that is often overlooked by PHP developers focused solely on building web applications. However, tapping into PHP‘s CLI abilities can unlock new ways of using PHP for automation, testing, and tooling. This comprehensive guide will explore the ins and outs of running PHP scripts from the command line.
An Introduction to PHP CLI
PHP CLI refers to the ability to run PHP scripts directly from a terminal or command prompt, without needing a web server or browser. The CLI SAPI (Server Application Programming Interface) was introduced in PHP 4.2.0, enabling developers to leverage PHP‘s capabilities for command line scripting and tooling.
Some key benefits of PHP CLI include:
- Automation – Script cron jobs, tasks, and system commands without needing a web frontend
- Testing – Validate code and simulate requests without spinning up a web server
- Tooling – Create custom command line utilities, shells and tools leveraging PHP
- Flexibility – Tap into PHP from more environments since a web server is not required
- Performance – Less overhead compared to using PHP via Apache/Nginx in some cases
PHP CLI opens up entire new categories of uses for PHP beyond just web development.
When to Use PHP CLI
Here are some common use cases where leveraging PHP CLI makes sense:
- Automation scripts – Script cron jobs, import/export scripts, maintenance routines etc.
- Command line utilities – Customer CLI tools for tasks like project scaffolding
- Background workers – Long running processing jobs handled in the background
- Testing scripts – Test code and simulate API requests without needing a HTTP server
- Data processing – Operate on CSV, JSON etc data from a terminal
- Code generation – Scripts that auto generate various kinds of files
- Sysadmin scripts – Automate Linux/Windows server management tasks
And many more system administration, DevOps, scripting and developer use cases.
Understanding the PHP CLI Process Lifecycle
When a PHP script runs from the command line rather than within a web server environment, the lifecycle of the PHP process is quite different.
There is no web server or browser involved. The PHP CLI binary executes your script directly, manages the process, and outputs responses to the terminal/command prompt window. Requests do not flow through Apache modules and response handling only needs to output data to stdout or stderr.
The PHP process initializes, loads any extensions, executes the script code, handles shutdown routines and exits. Runtime options can be passed to the PHP CLI binary to control error reporting, output handling, script execution and more. Exit codes provide status and error handling upon script completion.
Understanding this simplified CLI request cycle is key to leveraging PHP effectively without a web frontend.
Installing and Configuring PHP CLI
Most modern PHP distributions come with the CLI binary included, but you still need to check if it is installed and available on your system PATH.
On Linux or OSX systems, running php -v will output the version if PHP cli is configured properly:
php -v
PHP 7.2.5 (cli) (built: May 15 2018 08:44:26) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
The php.ini used by the CLI can differ from the web server configuration since it runs as a separate process. On Linux systems, the default location is at /etc/php/{php_version}/cli/php.ini
This configuration handles error reporting, script timeouts, memory limits and other runtime options. Tune these appropriately for your scripts.
For running more complex scripts, extensions like PDO, Json, OpenSSL etc might be needed. Enable CLI specific extensions in the php.ini:
[PHP_CLI_EXTENSIONS]
extensions=php_pdo_mysql.dll
extension=php_openssl.dll
With PHP CLI installed and configured, you are ready to start executing PHP scripts from the comfort of your terminal!
Executing PHP Scripts from the Command Line
There are a couple ways to directly run PHP scripts from the command line:
1. Using the php Command
The php command followed by script path runs the code with the CLI interpreter:
$ php myscript.php
This method works across all platforms and allows passing runtime options too:
$ php -f myscript.php
2. Using a Shebang Line
On *nix systems, starting PHP scripts with a shebang line allows scripts to be run directly:
#!/usr/bin/env php
<?php
// Rest of PHP code
Make sure to make the script executable:
$ chmod +x myscript.php
$ ./myscript.php
This helps create self-contained, portable PHP scripts.
Essential CLI Parameters and Options
PHP CLI provides many useful parameters to control script execution. The most important ones to know:
- -a – Run interactively from stdin
- -f – Parse and execute a PHP script file path
- -l – Syntax check only (lint)
- -r – Run PHP code without tag wrappers
- -B – Run in batch mode (disable output)
- -n – Do not use php.ini configuration
- -d – Define INI entry as key=value
- -e – Generate extended information for debuggers
These options greatly expand the flexibility of running PHP from the terminal.
Handling Input and Output Streams
Without a web server handling requests and responses, input and output needs to be managed directly within CLI scripts:
- Standard input (STDIN) can be read for user input via fgets()/fread()
- Standard output (STDOUT) via print(), echo displays output
- Standard error (STDERR) outputs errors separately from standard output
- Exit codes should be set properly for script status
Example reading input and writing output:
// Get input
$name = fgets(STDIN);
// Write output
fwrite(STDOUT, "Hello ${name}!");
Managing I/O is vital for effective PHP CLI scripting.
Accessing Command Line Arguments and Environment
When executing from the command prompt, scripts can access passed command line arguments as well as environment information:
$ php myscript.php john snow
Arguments are available in the $argv array:
$firstName = $argv[1];
$lastName = $argv[2];
Server $_ENV variables provide environment information like user, paths, shell etc.:
$user = $_ENV[‘USER‘];
$home = $_ENV[‘HOME‘];
Tapping into this context data opens up more possibilities.
Generating Machine Readable Output
Since CLIs lack UI, it is common to output data in machine friendly formats like JSON, XML, CSV etc:
/** @var array $data */
// JSON encode output
echo json_encode($data);
// Fputcsv to generate CSV data
fputcsv(STDOUT, $data);
This allows other scripts to consume the output programmatically.
Handling Errors and Logging
Robust error handling and logging is important for CLI scripts:
- Use exit codes to provide script status – 0 for success
- Print user facing errors to STDERR
- Use try/catch blocks and exceptions for control flow
- Dump debug level logs to a file
Examples:
// Status exit
exit(1);
// Error output
fwrite(STDERR, $error);
// Exception handling
try {
// code
}
catch (Exception $e) {
// log error
}
// File logger
error_log("Message", 3, "/tmp/app.log");
This helps surface issues when running unattended scripts.
Creating Your Own CLI Tools
Once comfortable with PHP CLI scripting, you can start building custom CLI utilities leveraging your existing PHP skills:
wp-cli tool for WordPress automation
phing build tool inspired by Ant
phpunit for testing
composer for dependency management
phar for self-contained PHAR utilities
The ecosystem of CLI tools built with PHP is vast – no need to reinvent the wheel!
Leveling Up: REPL, Shells and Scripting
For more advanced use cases, PHP CLI allows creating interactive Read–eval–print loop (REPL) shells and straight up shell scripting:
- php -a for a PHP CLI shell
- phpsh for an integrated shell environment in PHP
- Shebang #!/usr/bin/php and chmod +x for shell scripting
This unlocks the full power of scripting directly in PHP beyond web apps.
Deployment and Integration
A huge benefit of CLI scripts is how easily they integrate into automated environments:
- Call PHP scripts from cron
- Run scripts in Docker containers
- Add to CI/CD pipelines with Jenkins, CircleCI etc.
- Trigger via aws lambda functions
- Execute from within app code using exec(), passthru() etc.
No GUI or web server makes PHP CLI a perfect fit for DevOps toolchains.
PHP CLI Brings the Best Out of PHP
The PHP CLI SAPI brings a whole new level of versatility to PHP usage outside traditional web contexts. Core language strengths like simplicity, ubiquity, speed and ecosystem stand out sharply when PHP tackles command line tasks.
Whether it is gluing systems together via scripts, writing handy utilities or building full blown CLI applications, PHP on the terminal empowers you do to more. The command line awakens the latent general purpose scripting potential within PHP.
So next time you find yourself writing up a Bash script, consider taking advantage of the comfort and capability of PHP instead!


