Writing PHP CLI Scripts for Cron Jobs

PHP isn’t just for web requests — running PHP scripts from the command line via cron is a common pattern for scheduled maintenance tasks, especially in codebases that already have business logic written in PHP.

#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';

$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$stmt = $pdo->prepare("DELETE FROM sessions WHERE last_activity < ?");
$stmt->execute([time() - 86400]);

echo "Deleted {$stmt->rowCount()} expired sessions\n";
# Run the cleanup script every night at 3 AM
0 3 * * * /usr/bin/php /var/www/app/scripts/cleanup-old-sessions.php >> /var/log/cleanup.log 2>&1

Add #!/usr/bin/env php as the first line and chmod +x the script to run it directly as ./script.php, or always invoke it explicitly with php in the crontab entry — the latter is safer since it doesn’t depend on execute permissions surviving a deploy.