7 questions found
How do you run a PHP script from the command line, and how does this differ from running PHP through a web server?
Beginner
You run a PHP script from the command line by invoking the php executable followed by the script's file name, and unlike running PHP through a web server, a command line script does not have access to web specific superglobals like $_GET or $_POST, does not automatically output HTTP headers, and instead typically receives input through command line arguments and produces output directly to the terminal, making it well suited for administrative tasks, scheduled jobs, and automation scripts.
php script.php arg1 arg2
Real-world example
A developer writes a simple PHP script to clean up old temporary files on a server, running it directly from the command line as a scheduled maintenance task rather than exposing it as a web accessible page.
Common follow-ups: What is the $argv superglobal and how does it relate to command line arguments?;Can the same PHP codebase be used for both web requests and command line scripts?
PHP CLI Scripting;Functions & Scope
How do you access command line arguments passed to a PHP script using the $argv and $argc superglobals?
Beginner
The $argv superglobal is an array containing every argument passed to the script from the command line, with the first element always being the script's own file name, and $argc contains the total count of those arguments, together letting your script read and respond to whatever specific arguments were provided when it was invoked, similar to how a web script reads data from $_GET or $_POST.
// Running: php greet.php Ali
echo "Script name: $argv[0]";
echo "First argument: $argv[1]";
echo "Total arguments: $argc";
Real-world example
A backup script reads the target directory to back up directly from a command line argument, letting the same script be reused flexibly for different directories simply by changing the argument provided each time it is run.
Common follow-ups: How do you provide default values for optional command line arguments that were not supplied?;What is the difference between $argv and using PHP's more structured getopt function?
Functions & Scope;File Handling & File System Functions
How does the getopt function provide a more structured way to parse command line options and flags compared to manually processing the $argv array?
Intermediate
The getopt function lets you define a set of expected short and long option flags, such as a verbose flag or an option requiring a value like a specific output file path, and automatically parses the actual command line arguments according to those defined expectations, returning a clean associative array of the options that were actually provided, which is significantly more robust and readable than manually looping through and interpreting the raw $argv array yourself for anything beyond the simplest scripts.
$options = getopt('v', ['output:']);
if (isset($options['v'])) {
echo 'Verbose mode enabled';
}
$outputFile = $options['output'] ?? 'default.txt';
Real-world example
A data export script uses getopt to support both a short verbose flag and a longer output option specifying the destination file, giving users a familiar, standard command line interface similar to other common command line tools.
Common follow-ups: What is the difference between a flag that requires a value and one that does not in getopt?;Are there third party libraries that provide even more advanced command line argument parsing than getopt?
Basics & Types;Deployment & Hosting for PHP Applications
How do PHP frameworks like Laravel's Artisan or Symfony's Console component let you build well structured, reusable custom command line commands?
Intermediate
Rather than writing standalone command line scripts from scratch, frameworks like Laravel and Symfony provide a structured console component that lets you define a custom command as a proper class, complete with built in support for arguments, options, formatted output, and progress bars, integrating that command directly into the framework's existing service container and configuration, letting your command line tools benefit from the same dependency injection and code organization as the rest of your application.
class SendNewsletterCommand extends Command {
protected $signature = 'newsletter:send {--dry-run}';
public function handle() {
$this->info('Sending newsletter...');
}
}
Real-world example
A Laravel application defines a custom Artisan command for sending a scheduled newsletter, taking advantage of the framework's existing email service and database models directly within the command, rather than duplicating that setup in a standalone script.
Common follow-ups: How do you register a custom command so it becomes available through Artisan or the Symfony console?;What built in features does a framework's console component typically provide beyond basic argument parsing?
Laravel Framework Essentials;Symfony Framework Essentials
How do you schedule a PHP script to run automatically at regular intervals using cron on a Linux server?
Intermediate
Cron is a standard Linux utility for scheduling recurring tasks, and you can configure it to run a PHP script at specific times or intervals, such as every night at midnight, by adding an entry to the system's crontab file specifying the schedule and the exact command to run, which is commonly used for tasks like sending scheduled reports, cleaning up old data, or triggering a queued job processor at regular intervals.
# Crontab entry running a script every night at midnight
0 0 * * * /usr/bin/php /var/www/scripts/cleanup.php
Real-world example
A company schedules a PHP script to run automatically every night through cron, generating and emailing a daily sales summary report to management without requiring anyone to manually trigger it each day.
Common follow-ups: What does each field in a standard crontab schedule entry represent?;How do modern frameworks like Laravel provide their own built in task scheduling on top of a single cron entry?
Deployment & Hosting for PHP Applications;Email Sending in PHP (PHPMailer & SMTP)
How should a long running PHP CLI script, such as a queue worker, handle graceful shutdown when it receives a termination signal from the operating system?
Advanced
A long running script can register signal handlers using PHP's pcntl extension to listen for signals like SIGTERM, which is typically sent by process managers or deployment tools requesting a graceful shutdown, allowing the script to finish processing its current unit of work, clean up any open resources like database connections, and exit cleanly, rather than being abruptly killed mid task, which could leave data in an inconsistent state.
pcntl_signal(SIGTERM, function () {
echo 'Shutting down gracefully...';
exit(0);
});
while (true) {
pcntl_signal_dispatch();
processNextJob();
}
Real-world example
A queue worker script registers a SIGTERM signal handler, ensuring that when a deployment process asks it to stop, it finishes processing its current job completely before shutting down, rather than potentially leaving a job half processed.
Common follow-ups: What is the difference between SIGTERM and SIGKILL in terms of how a process can respond?;Why is the pcntl extension not available in all PHP environments, such as certain shared hosting setups?
Deployment & Hosting for PHP Applications;Asynchronous PHP (ReactPHP & Swoole)
What memory management considerations apply specifically to long running PHP CLI scripts, such as queue workers, that might process thousands of jobs without ever restarting?
Advanced
Unlike a typical web request where PHP's memory is completely reset at the end of every single request, a long running CLI process accumulates memory usage across many iterations of its main loop, meaning any unintentional memory leak, such as an ever growing array or unreleased resource, can gradually consume all available memory over time, which is why long running workers often include periodic memory usage monitoring and are commonly configured to automatically restart themselves after processing a certain number of jobs, providing a clean memory reset on a predictable schedule.
$jobsProcessed = 0;
while (true) {
processNextJob();
$jobsProcessed++;
if ($jobsProcessed >= 1000 || memory_get_usage() > 256 * 1024 * 1024) {
exit(0); // process manager restarts a fresh worker
}
}
Real-world example
A queue worker configured to automatically exit after processing one thousand jobs, with a process manager immediately restarting a fresh worker process, avoids a subtle memory leak in a third party library from ever accumulating enough to cause an actual out of memory crash.
Common follow-ups: What tools help detect a specific memory leak within a long running PHP process?;How does a process manager like Supervisor help automatically restart a worker process that has exited?
Performance Optimization & OPcache;Asynchronous PHP (ReactPHP & Swoole)