PHP Command Line Interface (CLI)
PHP is not just for web pages; it can also be run from the command line to create scripts, cron jobs, and utilities.
1. Running Scripts
To run a PHP script from the command line, use the php command followed by the filename.
php script.php
2. Command Line Arguments
PHP provides two special variables to handle arguments passed to a script:
$argc: The number of arguments passed (integer).$argv: An array of the arguments. Note that$argv[0]is always the name of the script itself.
script.php:
<?php
echo "Script name: " . $argv[0] . "\n";
if ($argc > 1) {
echo "Hello, " . $argv[1] . "!\n";
}
?>
Command:
php script.php John
Output:
Script name: script.php
Hello, John!
3. Interactive Input (STDIN)
You can read input from the user using the STDIN constant or readline().
echo "Are you sure you want to continue? (y/n): ";
$input = trim(fgets(STDIN));
if ($input == 'y') {
echo "Continuing...\n";
} else {
echo "Aborted.\n";
}
4. Built-in Web Server
PHP has a built-in web server useful for local testing without installing Apache or Nginx.
# Start server on localhost port 8000
php -S localhost:8000
5. Common Flags
php -v: Check PHP version.php -a: Interactive shell (REPL).php -i: Display PHP configuration (phpinfo).php -l file.php: Syntax check (lint) a file.