PHP is most commonly used to generate web pages, but it is also a capable command line scripting language. CLI PHP is used for database migrations, data imports, scheduled tasks, admin tools, and automation scripts. This guide covers building practical PHP CLI programs — from simple scripts to interactive tools and Laravel Artisan commands.
Table of Contents
Running PHP from the Command Line
php -v # PHP version
php -r "echo PHP_VERSION;" # Run inline PHP
php script.php # Run a PHP file
php -S localhost:8000 # Built-in development server
php -l script.php # Lint check (syntax only)
Command Line Input: $argv and $argc
#!/usr/bin/env php
<?php
// script.php — run as: php script.php arg1 arg2
// $argv = array of arguments (index 0 = script name)
// $argc = count of arguments
if ($argc < 3) {
echo "Usage: php {$argv[0]} <source> <destination>\n";
exit(1);
}
$source = $argv[1];
$destination = $argv[2];
echo "Copying {$source} to {$destination}\n";
Interactive Input with readline
#!/usr/bin/env php
<?php
// Read from stdin (works without readline extension):
function ask(string $prompt, string $default = ''): string {
$hint = $default !== '' ? " [{$default}]" : '';
echo $prompt . $hint . ': ';
$input = trim(fgets(STDIN));
return $input !== '' ? $input : $default;
}
function ask_secret(string $prompt): string {
echo $prompt . ': ';
system('stty -echo'); // Hide typing
$input = trim(fgets(STDIN));
system('stty echo');
echo "\n";
return $input;
}
function confirm(string $prompt, bool $default = false): bool {
$hint = $default ? '[Y/n]' : '[y/N]';
echo "$prompt $hint: ";
$input = strtolower(trim(fgets(STDIN)));
if ($input === '') return $default;
return $input === 'y' || $input === 'yes';
}
$name = ask('Your name', 'Lyndon');
$email = ask('Email address');
$password = ask_secret('Password');
if (!confirm("Create account for {$email}?")) {
echo "Cancelled.\n";
exit(0);
}
echo "Account created for {$name}!\n";
ANSI Colors for Terminal Output
class CLI {
const RED = "\033[0;31m";
const GREEN = "\033[0;32m";
const YELLOW = "\033[1;33m";
const BLUE = "\033[0;34m";
const BOLD = "\033[1m";
const RESET = "\033[0m";
public static function success(string $msg): void {
echo self::GREEN . "✓ " . self::RESET . $msg . "\n";
}
public static function error(string $msg): void {
echo self::RED . "✗ " . self::RESET . $msg . "\n";
exit(1);
}
public static function warning(string $msg): void {
echo self::YELLOW . "⚠ " . self::RESET . $msg . "\n";
}
public static function info(string $msg): void {
echo self::BLUE . "→ " . self::RESET . $msg . "\n";
}
public static function progress(int $done, int $total, string $label = ''): void {
$pct = $total > 0 ? round(($done / $total) * 100) : 0;
$bar = str_repeat('█', (int)($pct / 5)) . str_repeat('░', 20 - (int)($pct / 5));
printf("\r%s [%s] %d/%d (%d%%)", $label, $bar, $done, $total, $pct);
if ($done === $total) echo "\n";
}
}
CLI::info("Starting database import...");
foreach ($records as $i => $record) {
import_record($record);
CLI::progress($i + 1, count($records), "Importing");
}
CLI::success("Imported " . count($records) . " records.");
Building an Argument Parser
function parse_args(array $argv): array {
$args = [];
$flags = [];
$options = [];
array_shift($argv); // Remove script name
for ($i = 0; $i < count($argv); $i++) {
$arg = $argv[$i];
if (str_starts_with($arg, '--')) {
$key = substr($arg, 2);
if (str_contains($key, '=')) {
[$k, $v] = explode('=', $key, 2);
$options[$k] = $v;
} elseif (isset($argv[$i + 1]) && !str_starts_with($argv[$i + 1], '-')) {
$options[$key] = $argv[++$i];
} else {
$flags[$key] = true;
}
} elseif (str_starts_with($arg, '-')) {
$flags[substr($arg, 1)] = true;
} else {
$args[] = $arg;
}
}
return compact('args', 'flags', 'options');
}
// Usage: php import.php users.csv --format=csv --dry-run -v
$parsed = parse_args($argv);
$file = $parsed['args'][0] ?? null;
$format = $parsed['options']['format'] ?? 'json';
$dry_run = isset($parsed['flags']['dry-run']);
$verbose = isset($parsed['flags']['v']);
Cron Jobs with PHP CLI
# Run a PHP script every day at 2am (crontab -e):
0 2 * * * /usr/bin/php /var/www/myapp/scripts/daily-report.php >> /var/log/daily-report.log 2>&1
# In Laravel — scheduled tasks replace manual cron setup:
# Add ONE cron entry:
* * * * * cd /var/www/myapp && php artisan schedule:run >> /dev/null 2>&1
// app/Console/Kernel.php — Laravel scheduled tasks:
protected function schedule(Schedule $schedule): void {
$schedule->command('reports:daily')->dailyAt('02:00');
$schedule->command('cleanup:old-logs')->weekly()->sundays()->at('03:00');
$schedule->job(new SendWeeklyNewsletter)->weeklyOn(1, '08:00'); // Monday 8am
}
Custom Laravel Artisan Commands
php artisan make:command SendDailyReport
// app/Console/Commands/SendDailyReport.php
class SendDailyReport extends Command {
protected $signature = 'reports:daily {--date= : Specific date (Y-m-d)}';
protected $description = 'Generate and email the daily activity report';
public function handle(): int {
$date = $this->option('date') ?? today()->toDateString();
$this->info("Generating report for: $date");
$this->withProgressBar(User::active()->cursor(), function (User $user) use ($date) {
Mail::to($user)->send(new DailyReport($date));
});
$this->newLine();
$this->info('Daily report sent successfully.');
return Command::SUCCESS;
}
}
Frequently Asked Questions
What can I build with PHP CLI?
Database seeders and importers, file processing scripts (CSV/XML import, image batch processing), scheduled reports sent via email, code generators, API clients that run on a schedule, log analysis tools, deployment scripts, and test data generators.
Is PHP good for CLI compared to Python or Bash?
For developers who primarily write PHP, PHP CLI is excellent — no language context switch, access to all your PHP classes and libraries (Eloquent, PHPMailer, etc.), and the same environment as your web application. Python is more powerful for data processing and system scripting. Bash is better for simple shell operations. PHP CLI is the right tool when you want to reuse your PHP codebase for background tasks.
Conclusion
PHP CLI opens up a category of tools that your web-facing PHP code cannot handle: scheduled data processing, interactive setup wizards, maintenance scripts, and report generation. The patterns here — parsing arguments, colorized output, progress bars, readline input — are what make CLI tools professional and usable. Laravel Artisan commands are the cleanest way to package this functionality in a Laravel project.
Next Step for Your Project Journey
Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

