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
Release: 2024-11-19 20:00:04
Original
881 people have browsed it

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template