Content · Web Development · PHP

Writing a Simple PHP CLI Script

A PHP CLI script reads arguments, writes standard output or errors, and returns meaningful exit codes for automation.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

A PHP CLI script reads arguments, writes standard output or errors, and returns meaningful exit codes for automation.

What It Does


Read CLI arguments from $argv only in command-line execution. Validate CLI options rather than trusting raw input.

Requirements and Compatibility


Use a supported PHP runtime and install any third-party tool or extension explicitly shown in the examples. Commands should be run from the project root unless stated otherwise.

Syntax, Inputs and Results


The examples separate configuration, the smallest working operation and a realistic follow-up task. Adapt file paths and dependency versions to your own project.

Example 1: Basic Use


Read CLI arguments from $argv only in command-line execution.

<?php
if (PHP_SAPI !== 'cli') { exit(1); }
$name = $argv[1] ?? 'guest';
echo 'Hello, ', $name, PHP_EOL;

Example 2: Another Case


Validate CLI options rather than trusting raw input.

<?php
$options = getopt('', ['dry-run', 'limit:']);
$limit = filter_var($options['limit'] ?? 10, FILTER_VALIDATE_INT);
if ($limit === false || $limit < 1) { fwrite(STDERR, 'Invalid limit' . PHP_EOL); exit(2); }
echo 'Processing up to ', $limit, PHP_EOL;

Practical Example


Lint a CLI script before invoking it with flags.

php -l bin/report.php
php bin/report.php --dry-run --limit=25

For production, apply the compatibility and edge-case limits described below.

Important Behavior and Edge Cases


Never assume $_GET and $_POST exist in command-line execution.

Comparison with Related Functions and Tools


SubjectKey difference
CLI vs web requestCLI receives argv and runs in a terminal; HTTP requests use a web server and request metadata.

Common Beginner Mistakes


MistakeCorrect approach
Expecting HTTP superglobals in terminal scriptsRead command arguments from $argv or getopt and use standard output and exit codes.
Skipping the prerequisite of this specific workflowInstall or configure the named tool and confirm the example can actually run.
Ignoring edge conditionsNever assume $_GET and $_POST exist in command-line execution.

Key Takeaways


  • A PHP CLI script reads arguments, writes standard output or errors, and returns meaningful exit codes for automation.
  • Never assume $_GET and $_POST exist in command-line execution.
  • Keep application configuration, source code and validation tests under version control.

Use these examples as a starting point, then validate the result with the actual PHP build, dependencies and inputs used by your application.

Share this resourceSend this page to someone who may find it useful.