"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-12-21
Browse:913

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
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3