PHP Command Line (CLI)
In this page:
What is PHP CLI?
PHP CLI (Command Line Interface) runs a .php script directly from a terminal instead of routing it through a web server request — the right tool for background jobs, scheduled cron tasks, and one-off maintenance scripts that have no browser involved and don't need to produce HTML at all.
Example: What is PHP CLI?
<?php
echo "Running via CLI: no HTTP request, no HTML needed\n";
echo php_sapi_name();
?>
Login to try C/C++/Java/PHP code in the editor
Command Line Arguments
Every argument you type after the script's filename on the command line lands in the built-in $argv array, with $argv[0] always holding the script's own filename first. $argc gives you the total count, which is handy for validating that the expected number of arguments was actually supplied before the script proceeds.
Example: Command Line Arguments
<?php
// Simulated since no args are passed in this sandbox: php script.php foo bar
$argv = ['script.php', 'foo', 'bar'];
$argc = count($argv);
echo "Script: $argv[0], Arg count: $argc\n";
for ($i = 1; $i < $argc; $i++) {
echo "Arg $i: $argv[$i]\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Interactive CLI Input
Calling fgets(STDIN) pauses script execution and waits for the person running it to type a line and press Enter, which is what turns a script from a fire-and-forget tool into something that can prompt for confirmation or collect a value interactively mid-run.
Example: Interactive CLI Input
<?php
echo "Enter your name: ";
$name = trim(fgets(STDIN));
echo $name === '' ? "No input received" : "Hello, $name!";
?>
Login to try C/C++/Java/PHP code in the editor
CLI Color Formatting
Wrapping text in ANSI escape codes tells a compatible terminal to render it in color or with bold/underline styling, which makes warnings and errors visually jump out from ordinary log lines — genuinely useful once a script's output runs to more than a few scrollback screens.
Example: CLI Color Formatting
<?php
echo "\033[31mThis is red text\033[0m\n";
echo "\033[1mThis is bold text\033[0m";
?>
Login to try C/C++/Java/PHP code in the editor
Command Line Menu Loop
Looping around a routine that prints a menu, reads the operator's choice, and dispatches to the matching action turns a single-purpose script into a small interactive tool someone can drive by picking numbered options, without needing to remember command-line flags for every feature.
Example: Command Line Menu Loop
<?php
$options = ["1" => "View report", "2" => "Exit"];
$choice = "1"; // simulated selection
foreach ($options as $key => $label) {
echo "$key. $label\n";
}
echo "You chose: " . $options[$choice];
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: