Advertisement
Beginner PHP, PHP CLI Scripting

How do you run a PHP script from the command line, and how does this differ from running PHP through a web server?

Short answer

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…

Save PHP mock interview
Advertisement
AModel answer
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.
Example

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.
Likely 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?
Related topics