Command-line scripts
PHP works beyond the website. A script can be run from the terminal: import a file, send out emails, clean up old data, recalculate statistics. Such scripts do not depend on a browser and can run for as long as needed.
The examples are meant for the terminal and do not run here — run them on your machine.
Running
<?php
// hello.php
echo "Hello from the terminal!\n";php hello.phpThere is no <html> tag and no headers here: the output goes straight to the terminal. You add line breaks yourself — with \n or the PHP_EOL constant.
Arguments
Everything written after the file name goes into the $argv array. Element zero is the script name, and $argc is the number of elements:
<?php
// greet.php
if ($argc < 2) {
echo "Usage: php greet.php name\n";
exit(1);
}
echo "Hello, {$argv[1]}!\n";php greet.php AnnaReading input
A script can ask a question and wait for the answer. Input is read from the STDIN stream:
<?php
// ask.php
echo 'What is your name? ';
$name = trim(fgets(STDIN));
echo "Hello, $name!\n";fgets() returns the line together with the line break, so it is trimmed with trim().
Errors and the exit code
Error messages are written to the separate STDERR stream, and the script ends with a code: 0 means success, any other number a failure:
<?php
// import.php
$file = $argv[1] ?? '';
if (!is_file($file)) {
fwrite(STDERR, "File not found: $file\n");
exit(1);
}
echo 'Lines: ', count(file($file)), "\n";
exit(0);Other programs — a scheduler, a deployment system — use the exit code to tell whether the operation worked.
Named parameters
The getopt() function parses parameters like --limit=10:
<?php
// export.php
$options = getopt('', ['limit:', 'format::', 'verbose']);
$limit = (int) ($options['limit'] ?? 100);
$format = $options['format'] ?? 'csv';
$verbose = isset($options['verbose']);
echo "Format: $format, records: $limit\n";php export.php --limit=10 --format=json --verboseOne colon after a name means the value is required, two that it is optional, and no colons mean a flag.
Useful PHP switches
| Command | What it does |
|---|---|
php -v | Shows the version |
php -l file.php | Checks the syntax without running |
php -r 'echo 2 + 2;' | Runs code from a string |
php -a | Interactive mode |
php -S localhost:8000 | Starts a development server |
php -m | Shows the loaded extensions |
Running on a schedule
On a server the cron scheduler runs scripts. A line in its table sets the time and the command:
0 3 * * * php /var/www/shop/cleanup.phpThis script runs every day at 3:00.
Common mistake
Relative paths in a script are resolved not from the file but from the folder it was started in. file('data.csv') finds the file when run from the project folder and fails from cron. Build paths from the __DIR__ constant — the folder where the script itself lives:
<?php
// report.php
$rows = file(__DIR__ . '/data.csv');