Home >Backend Development >PHP Tutorial >How to Reliably Determine if a PHP Script Is Running in Command-Line or HTTP Mode?

How to Reliably Determine if a PHP Script Is Running in Command-Line or HTTP Mode?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 20:00:04882browse

How to Reliably Determine if a PHP Script Is Running in Command-Line or HTTP Mode?

Determining Command-Line vs. HTTP Execution in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn