Home > Article > Backend Development > How to Determine if a PHP Script is Running on the Command Line or via HTTP?
Determining Script Execution Mode in PHP
Determining whether a PHP script is executed via the command-line or HTTP is crucial for various purposes, such as output formatting. Historically, checking the SERVER['argc'] variable was thought to be the canonical approach. However, this method proves unreliable when using the Apache 2.0 Handler server API as it populates SERVER['argc'] even in command-line execution.
The recommended and more robust method is to utilize the php_sapi_name() function. It returns a string indicating the type of interface between the web server and PHP. Examples include:
Example Code:
if (php_sapi_name() == "cli") { // In cli-mode } else { // Not in cli-mode }
Documentation Notes:
The php_sapi_name() function documentation provides further information:
The above is the detailed content of How to Determine if a PHP Script is Running on the Command Line or via HTTP?. For more information, please follow other related articles on the PHP Chinese website!