Home >Backend Development >PHP Tutorial >How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?
Distinguishing Command-Line Execution from HTTP Execution in PHP
Determining whether a PHP script is executed via the command line or HTTP request is essential for customizing output formats. While inspecting the SERVER['argc'] variable may seem like a valid approach, it's not always accurate, even with Apache's 'Apache 2.0 Handler' server API.
The canonical method to accomplish this task is the php_sapi_name() function.
if (php_sapi_name() == "cli") { // In cli-mode } else { // Not in cli-mode }
As specified in the PHP documentation:
php_sapi_name returns the type of interface between the web server and PHP.
Possible return values include "apache2handler," "cgi," "cli," "isapi," "litespeed," etc.
Alternatively, you can use the PHP_SAPI constant, which has the same value as php_sapi_name(), introduced in PHP version 4.2.0.
The above is the detailed content of How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?. For more information, please follow other related articles on the PHP Chinese website!