Skip to main content

Lesson 3 of 6

PHP CLI - Scripts, Cron Jobs & Commands

PHP runs outside the web server via the CLI SAPI. CLI scripts power cron jobs, queue workers, database migrations, data imports, report generation, and maintenance tasks. Understanding the differences between CLI and web execution and building clean command-line tools is essential for real-world PHP backend work.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

PHP CLI Scripts, Arguments & Cron Integration

PHP CLI Scripts, Arguments & Cron Integration
#!/usr/bin/env php
<?php
declare(strict_types=1);

// ── Running PHP via CLI ────────────────────────────────────────
// php script.php
// php script.php --env=production --limit=100
// php -r "echo PHP_VERSION;"        (single line)
// php -l file.php                   (syntax check)
// php -a                            (interactive REPL)

// ── CLI vs Web differences ────────────────────────────────────
if (PHP_SAPI !== "cli") {
    echo "This script must be run from the command line.
";
    exit(1);
}

// CLI: no $_GET, $_POST, $_SESSION, $_COOKIE
// CLI: no HTTP headers
// CLI: infinite execution time (unless you set it)
// CLI: STDIN, STDOUT, STDERR streams available
// CLI: $argc, $argv - argument count and values
// CLI: no output buffering by default

// ── Argument parsing ──────────────────────────────────────────
// php publish-posts.php --limit=50 --dry-run --env=production
$options = getopt("", ["limit:", "dry-run", "env:"]);
$limit   = (int) ($options["limit"] ?? 10);
$dryRun  = isset($options["dry-run"]);
$env     = $options["env"] ?? "production";

echo "Publishing up to $limit posts" . ($dryRun ? " [DRY RUN]" : "") . "...
";

// ── Output - use STDOUT/STDERR appropriately ──────────────────
fwrite(STDOUT, "Starting publish job...
");
fwrite(STDERR, "WARNING: rate limit reached
");  // errors to stderr

// ── Progress bar for long-running operations ──────────────────
function progressBar(int $current, int $total, int $width = 40): void {
    $percent = $total > 0 ? (int) ($current / $total * 100) : 0;
    $filled  = (int) ($current / $total * $width);
    $bar     = str_repeat("█", $filled) . str_repeat("░", $width - $filled);
    echo "
[$bar] $percent% ($current/$total)";
    if ($current === $total) echo "
";
}

$posts = $pdo->query("SELECT id FROM posts WHERE status = 'draft' ORDER BY created_at ASC LIMIT $limit")->fetchAll();
$total = count($posts);

foreach ($posts as $i => $row) {
    if (!$dryRun) {
        $pdo->prepare("UPDATE posts SET status='published', published_at=UTC_TIMESTAMP() WHERE id=:id")
            ->execute([":id" => $row["id"]]);
    }
    progressBar($i + 1, $total);
    usleep(50_000);  // 50ms between operations - be gentle on DB
}

echo "Done: $total posts " . ($dryRun ? "would be" : "were") . " published.
";
exit(0);

// ── Exit codes - important for cron and CI ────────────────────
// 0 = success (cron and scripts expect 0 = OK)
// 1 = general error
// 2 = misuse of shell command (wrong arguments)
// Custom: your own error classification

// ── Cron job configuration ────────────────────────────────────
# Edit with: crontab -e

# Format: minute  hour  day-of-month  month  day-of-week  command

# Run every hour
0 * * * * /usr/bin/php /var/www/html/cli/publish-posts.php >> /var/log/blog-cron.log 2>&1

# Run at 2:30 AM every day
30 2 * * * /usr/bin/php /var/www/html/cli/cleanup-sessions.php >> /var/log/cron.log 2>&1

# Run every 5 minutes
*/5 * * * * /usr/bin/php /var/www/html/cli/process-queue.php

# With env file loading (required - cron has no .env)
0 * * * * cd /var/www/html && /usr/bin/php cli/publish-posts.php --env=production

<?php
// ── CLI command class - structured approach ───────────────────
abstract class Command {
    abstract public function handle(array $options): int;

    protected function info(string $msg): void  { fwrite(STDOUT, "[INFO] $msg
"); }
    protected function error(string $msg): void { fwrite(STDERR, "[ERROR] $msg
"); }
    protected function line(string $msg): void  { fwrite(STDOUT, "$msg
"); }
}

class PublishDraftPostsCommand extends Command {
    public function __construct(private readonly PDO $pdo) {}

    public function handle(array $options): int {
        $limit  = (int) ($options["limit"] ?? 10);
        $dryRun = isset($options["dry-run"]);

        $this->info("Looking for draft posts to publish (limit: $limit)" . ($dryRun ? " [DRY RUN]" : ""));

        $posts = $this->findScheduledPosts($limit);
        if (empty($posts)) { $this->info("No posts to publish."); return 0; }

        foreach ($posts as $post) {
            $this->line("  Publishing: {$post['title']} (id={$post['id']})");
            if (!$dryRun) $this->publish($post["id"]);
        }
        $this->info("Processed " . count($posts) . " posts.");
        return 0;
    }

    private function findScheduledPosts(int $limit): array { /* ... */ return []; }
    private function publish(int $id): void { /* ... */ }
}

Quick Quiz

Tip

Tip

Practice PHP CLI Scripts Cron Jobs Commands in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for PHP CLI - Scripts, Cron Jobs & Commands

Practice Task

Note

Practice Task - (1) Write a working example of PHP CLI Scripts Cron Jobs Commands from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with PHP CLI Scripts Cron Jobs Commands is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/6 done