Home >Backend Development >PHP Tutorial >How to Reliably Determine if a PHP Script Is Running in Command-Line or HTTP Mode?
In PHP, determining whether a script is being executed from the command-line or via HTTP is essential for output formatting and other purposes. The traditional method of inspecting the SERVER['argc'] array is not reliable in all cases, as it may be populated even during HTTP execution.
The canonical solution to this problem is to use the php_sapi_name() function. This function returns the interface type between the web server and PHP. If the returned value is "cli", the script is being executed from the command-line, while any other value indicates HTTP execution.
if (php_sapi_name() == "cli") { // In cli-mode } else { // Not in cli-mode }
As noted in the PHP documentation, php_sapi_name() can return various values depending on the server interface. Some common values include "apache", "cgi-fcgi", "nsapi", and "litespeed".
In PHP versions 4.2.0 and above, there is also a predefined constant PHP_SAPI that has the same value as php_sapi_name(). This constant can be used as an alternative to the function.
The above is the detailed content of How to Reliably Determine if a PHP Script Is Running in Command-Line or HTTP Mode?. For more information, please follow other related articles on the PHP Chinese website!