Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 147 ยท Advanced PHP

Command-Line PHP

Write command-line tools in PHP - read arguments with $argv and getopt, use STDIN, STDOUT and STDERR, return exit codes, prompt for input and handle signals.

PHP is best known for web pages, but the same language runs perfectly well in a terminal. Every PHP install includes the CLI (command-line interface) version of PHP, and it powers far more than you might expect: Composer is a PHP command-line program, frameworks ship console tools like php artisan and bin/console, and most PHP applications have scripts that import data, send queued emails or clean up old records at night.

A command-line script differs from a web page in a few important ways. There's no browser and no HTTP request: input comes from arguments and standard input, output goes to standard output and standard error, and the script reports success or failure with an exit code. There's also no time limit by default. This lesson covers all of it, then puts the pieces together into a small, well-behaved tool.

Our editor runs your code with the PHP CLI, so everything here is real command-line PHP. The one thing the editor can't do is pass arguments to your script, so you'll learn how to simulate them, which turns out to be a good design habit anyway.

Running PHP from the terminal

You run a script by passing its file name to the php binary. A few other options are worth knowing from day one:

Terminal
php report.php                 # run a script
php report.php --month=2026-09 # run it with arguments
php -r 'echo PHP_VERSION, "\n";'   # run a one-line snippet (no <?php tag)
php -l report.php              # lint: check the syntax without running
php -a                         # interactive shell (needs the readline extension)
php -m                         # list loaded extensions
php --ini                      # show which php.ini files are loaded
php -S localhost:8000          # built-in development web server

php -l is handy in scripts and Git hooks: it prints No syntax errors detected in report.php or the parse error with its line number. The built-in web server from How PHP Works is for development only.

Your script can ask which SAPI (server API) it's running under. PHP_SAPI is 'cli' on the command line and something like 'fpm-fcgi' under PHP-FPM, which lets a script refuse to run in the wrong place:

PHP Arguments in the editor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$argv and $argc

On the command line PHP fills two variables for you before your code starts:

  • $argv is an array of strings: the script name first, then each argument in order.
  • $argc is the number of elements in $argv, so it's always at least 1.

In the editor the script is called main.php and receives no arguments, so you saw $argc as 1 and $argv containing only main.php. If you ran php greet.php Ada "Grace Hopper" 42 in a terminal, you'd get:

TEXT
Array
(
    [0] => greet.php
    [1] => Ada
    [2] => Grace Hopper
    [3] => 42
)

Notice three things. The shell splits arguments on spaces, so quotes keep Grace Hopper together and are removed before PHP sees them. Every argument is a string, including 42, so convert and validate numbers yourself. And $argv exists only in the global scope; inside a function, pass it in as a parameter (or read $_SERVER['argv']).

That last point leads to the best way to structure a CLI script: put the real work in a function that receives the argument list and returns an exit code. Then the top of the file is a single line that hands over the real $argv, and you can call the same function with any list you like. That's how the rest of this lesson simulates arguments:

PHP Simulating command-line arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Parsing options with getopt()

Real tools take options as well as plain arguments: short flags like -v, long options like --format=json, and options with values. PHP's built-in getopt() parses them from the real command line:

PHP
<?php
// php export.php -v --format=json --limit 50 users.csv
$rest = 0;
$options = getopt('vh', ['format:', 'limit:', 'dry-run'], $rest);
$files = array_slice($argv, $rest);

// $options = ['v' => false, 'format' => 'json', 'limit' => '50']
// $files   = ['users.csv']

The first argument lists short options, one letter each; the second lists long options. A suffix of : means "requires a value", :: means "optional value", and no suffix means a flag. Flags show up with the value false (just check isset($options['v'])); options you didn't pass are missing from the array. The third argument receives the index where parsing stopped, so array_slice($argv, $rest) gives you the remaining file names.

getopt() always reads the real command line, not your $argv variable, so in the editor it returns an empty array. When you want options you can test, a short parser of your own works on any list:

PHP A small option parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For anything bigger than a few options, use a library. symfony/console (used by Laravel's Artisan and Symfony) gives you argument definitions, validation, generated --help pages, colors, tables and progress bars. It's installed with Composer (Autoloading and Composer).

STDIN, STDOUT and STDERR

Every program starts with three open streams. The PHP CLI gives you constants for them:

Constant Stream Used for
STDIN standard input data piped in, or what the user types
STDOUT standard output the program's results (echo writes here)
STDERR standard error errors, warnings and progress messages

Keeping results and messages on separate streams is what makes tools combine well. In php export.php > users.json, the shell sends STDOUT to the file while STDERR still appears on the screen, so a warning never corrupts your JSON. Write messages with fwrite(STDERR, ...).

Reading from STDIN lets your tool sit in a pipeline like cat access.log | php top-pages.php. fgets(STDIN) returns one line at a time, including its newline, and false at the end of the input. The Input box under the editor plays the role of the piped data:

PHP A filter that reads STDIN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The results (/home 3 times, /pricing 2 times) go to STDOUT, and the skipped lines and the line count go to STDERR, which the editor shows separately. To read all input at once, use stream_get_contents(STDIN); for big inputs, line by line keeps memory flat. Streams and Wrappers covers the php://stdin, php://stdout and php://stderr wrappers behind these constants.

STDIN, STDOUT and STDERR exist only in the CLI. In a web request, use fopen('php://stdin', 'r') and friends if you ever need them, though web code rarely does.

Asking the user questions

An interactive script prints a prompt and reads the answer with fgets(STDIN). Always trim() the answer (it ends with a newline) and handle false, which means the input ended, for example when a user presses Ctrl+D or when the script runs from cron with no input at all. Writing the prompt to STDERR keeps it out of any output you redirect to a file:

PHP Prompting for input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first answer is an empty line, so the default demo-app is used; then come large and yes. Change the Input box to try other answers. The prompts appear in the STDERR output because no one is typing at a terminal here. For hidden input such as passwords, real tools turn off terminal echo (stty -echo on Linux and macOS, or a library like symfony/console), which an editor without a terminal can't show.

Exit codes

When a program finishes, it hands the shell a number from 0 to 255. 0 means success; anything else means failure, and tools often use different numbers for different problems (by convention, 1 is a general error and 2 is a usage error). Shells, cron, CI pipelines and deploy scripts all check this number: php migrate.php && php deploy.php runs the deploy only if the migration exits with 0.

exit() ends the script. Given an integer, it becomes the exit code; given a string, PHP prints the string and exits with 0, which is a common bug when people write exit('Error!') and their CI pipeline reports success. die() is an alias of exit(). Since PHP 8.4, exit() behaves like a regular function, so its argument follows normal type rules.

A script that runs to the end exits with 0. An uncaught exception or fatal error exits with 255. Our editor shows a note when a program's exit code isn't 0:

PHP Returning an exit code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The argument thirty isn't a number, so the script prints its usage message to STDERR and exits with code 2; the editor reports "The program exited with code 2." Change 'thirty' to '30' and it exits normally.

Making a script executable

On Linux and macOS you can run a PHP script directly, like any other command. Add a shebang line as the very first line, above <?php, and mark the file executable:

PHP
#!/usr/bin/env php
<?php
declare(strict_types=1);

// ... your tool
Terminal
chmod +x bin/cleanup
./bin/cleanup 30

/usr/bin/env php finds php on the user's PATH, so the script works wherever PHP is installed. The PHP CLI skips the shebang line instead of printing it. Tools usually drop the .php extension (bin/cleanup, artisan) because users don't care what language a command is written in. On Windows, run them as php bin/cleanup 30.

Long-running scripts, cron and signals

The CLI sets max_execution_time to 0 (no limit), so a script can run for hours. That's ideal for imports and queue workers, but it brings two concerns.

First, memory: a worker that processes jobs forever must not accumulate data. Process items in batches, unset big variables, and let a supervisor restart the worker every few hundred jobs, which is what Laravel's queue:work --max-jobs and Symfony Messenger's --limit do.

Second, stopping cleanly. When a server shuts down or a deploy restarts workers, the process receives a signal such as SIGTERM. The pcntl extension (Linux and macOS only) lets your script catch it, finish the current job and exit, instead of dying halfway through writing a file. This demo sends SIGTERM to itself to show the idea:

PHP Stopping gracefully on SIGTERM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The handler only sets a flag; the loop checks it between jobs, so job 3 finishes and the script stops cleanly after 3 jobs instead of 10.

Scheduled scripts usually run from cron. A crontab line has five time fields (minute, hour, day of month, month, day of week) and a command. Use absolute paths, because cron runs with a minimal environment, and send output to a log so failures leave a trace:

TEXT
# Every night at 03:15, delete old sessions
15 3 * * * /usr/bin/php /var/www/app/bin/cleanup 30 >> /var/log/app/cleanup.log 2>&1

Frameworks often install a single cron entry that runs their own scheduler every minute, then decide in PHP which tasks are due.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You run php tool.php report 2026 --dry-run. What is $argv[2]?

    $argv[0] is the script name, $argv[1] is 'report' and $argv[2] is '2026'. Arguments are always strings, so convert and validate numbers yourself.
  2. 2. A script ends with exit('Import failed');. What does a CI pipeline see?

    With a string, exit() prints it and exits with status 0. To signal failure, write the message to STDERR and call exit(1).
  3. 3. Why should a CLI tool write warnings to STDERR instead of with echo?

    Shells redirect STDOUT and STDERR separately. Results go to STDOUT; messages on STDERR never corrupt the data file or the next program in the pipeline.
  4. 4. In a loop reading while (($line = fgets(STDIN)) !== false), what makes the loop stop?

    An empty line is "\n", which is not false. fgets() returns false only at the end of input. The CLI has no time limit by default.
  5. 5. What is the advantage of putting the script's logic in function main(array $argv): int and ending with exit(main($argv));?

    Passing arguments in and returning a code keeps the logic independent of the real command line, so tests (and this editor) can call it with simulated arguments.

Summary

  • The PHP CLI runs scripts with php file.php; php -r, php -l, php -a, php -m and php --ini are useful extras. PHP_SAPI is 'cli' on the command line.
  • $argv holds the script name and the arguments as strings; $argc counts them. Structure tools as main(array $argv): int so the logic is testable with simulated arguments.
  • getopt() parses short and long options (: required value, :: optional) from the real command line; larger tools use symfony/console.
  • Read input from STDIN with fgets() (false at end of input) or stream_get_contents(). Send results to STDOUT and messages to STDERR.
  • Exit with 0 for success and non-zero for failure; exit('text') exits with 0. Uncaught errors exit with 255.
  • A #!/usr/bin/env php shebang plus chmod +x makes a script a command.
  • CLI scripts have no time limit: watch memory in long-running workers, handle SIGTERM with pcntl_signal() to stop cleanly, and schedule jobs with cron using absolute paths and a log file.

Next: What's New in PHP 8.0 to 8.5