Development
How to Build a PHP Command-Line Script

Build a PHP command-line script by defining its arguments, validating them before work starts, writing results to standard output, and sending diagnostics to standard error. Return an exit code that automation can use.
A command should be understandable from its invocation. Requiring an operator to remember which global variables to edit is a fragile interface.
Build a PHP command-line script with a small contract
This PHP 8.1+ script counts non-empty lines in one readable local file. Save it as count-lines.php:
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
http_response_code(404);
exit;
}
if ($argc !== 2 || in_array($argv[1], ['--help', '-h'], true)) {
$help = $argc === 2 && in_array($argv[1], ['--help', '-h'], true);
fwrite($help ? STDOUT : STDERR, "Usage: php count-lines.php FILE\n");
exit($help ? 0 : 2);
}
$path = $argv[1];
if (!is_file($path) || !is_readable($path)) {
fwrite(STDERR, "FILE must be a readable regular file.\n");
exit(2);
}
$handle = fopen($path, 'rb');
if ($handle === false) {
fwrite(STDERR, "Cannot open the input file.\n");
exit(1);
}
try {
$count = 0;
while (($line = fgets($handle)) !== false) {
if (trim($line) !== '') {
$count++;
}
}
if (!feof($handle)) {
throw new RuntimeException('Input could not be read completely.');
}
fwrite(STDOUT, $count . PHP_EOL);
} catch (Throwable $error) {
fwrite(STDERR, "Counting failed.\n");
exit(1);
} finally {
fclose($handle);
}
Run php count-lines.php --help, then supply a fixture file. With three non-empty lines and one empty line, the expected output is 3 and a successful exit status.
PHP documents the command environment, arguments, and standard streams in its command-line guide. This example deliberately avoids a framework so the contract remains visible.
Keep results separate from diagnostics
Standard output is the command's result. Standard error is where usage mistakes and operational diagnostics belong. A shell pipeline can then consume the number without also receiving a progress sentence.
The example reserves 0 for success, 2 for invalid invocation, and 1 for processing failure. These are this command's documented choices, not a universal PHP convention. Keep them stable when another program begins depending on the command.
Do not print credentials or full customer records in an exception message. In a larger application, send detailed, sanitized diagnostics to your operational logger and give the operator a correlation identifier.
Make automation independent of the current directory
An argument such as data/input.txt resolves relative to the process's working directory. That is appropriate when the operator supplies it knowingly. Application-owned configuration should instead resolve from a documented location, often anchored with __DIR__.
The CLI runtime can use a different PHP version, extension set, and configuration file from the web server. Check php --version, php --ini, and the required extensions in the environment where the scheduler runs.
If the command grows into a real application entry point, load Composer's autoloader once and keep domain work outside argument parsing. Do not introduce a command framework just to hide a small script's control flow.
Verify failure behavior as well as the happy path
Use a tiny fixture, an empty file, a missing path, and a directory. Confirm that invalid invocation produces no result on standard output and returns the documented status. On a Unix shell, inspect $? immediately after invoking the command.
For a command that writes data, add a bounded dry-run mode before automating it. Define how interruption, retries, and partial completion behave. Counting a file can be restarted cheaply; charging an invoice cannot simply be repeated without an idempotency design.
Can I invoke this through a web request?
This entry point rejects non-CLI requests, but it should also live outside the web document root. An internal tool still needs a deliberate access boundary and a clear owner.
For help turning maintenance scripts into reliable operational commands, discuss a focused PHP engagement.