Home > Backend Development > PHP Tutorial > How Can I Reliably Determine if My PHP Script is Running from the Command Line or via HTTP?

How Can I Reliably Determine if My PHP Script is Running from the Command Line or via HTTP?

Patricia Arquette
Release: 2024-11-16 12:13:03
Original
409 people have browsed it

How Can I Reliably Determine if My PHP Script is Running from the Command Line or via HTTP?

Determining Command-Line vs. HTTP Execution in PHP

A common task in PHP script development is determining the type of execution environment, whether the script is running via the command-line or through HTTP. This knowledge is crucial for making output-formatting decisions and customizing behavior accordingly.

The traditional method of checking the existence of SERVER['argc'] is not reliable, as it can be populated even when using the 'Apache 2.0 Handler' server API. The canonical way to resolve this query is by utilizing the php_sapi_name() function.

if (php_sapi_name() == "cli") {
    // In cli-mode
} else {
    // Not in cli-mode
}
Copy after login

The php_sapi_name() function provides a wide range of possible return values, including aolserver, apache, apache2filter, apache2handler, caudium, cgi, cli, and webjames, among others. Refer to the PHP documentation for an exhaustive list.

Moreover, in PHP >= 4.2.0, a predefined constant PHP_SAPI holds the same value as php_sapi_name(). By utilizing this constant, developers can improve code readability and maintainability.

By adhering to this canonical approach, PHP developers can reliably determine the execution environment of their scripts, allowing for targeted output formatting and tailored behavior adjustments.

The above is the detailed content of How Can I Reliably Determine if My PHP Script is Running from the Command Line or via HTTP?. 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