Home > Backend Development > PHP Tutorial > How to Determine if a PHP Script is Running on the Command Line or via HTTP?

How to Determine if a PHP Script is Running on the Command Line or via HTTP?

Barbara Streisand
Release: 2024-11-15 18:33:03
Original
897 people have browsed it

How to Determine if a PHP Script is Running on the Command Line or via HTTP?

Determining Script Execution Mode in PHP

Determining whether a PHP script is executed via the command-line or HTTP is crucial for various purposes, such as output formatting. Historically, checking the SERVER['argc'] variable was thought to be the canonical approach. However, this method proves unreliable when using the Apache 2.0 Handler server API as it populates SERVER['argc'] even in command-line execution.

The recommended and more robust method is to utilize the php_sapi_name() function. It returns a string indicating the type of interface between the web server and PHP. Examples include:

  • "cli" for command-line execution
  • "apache2handler" for Apache 2.0 Handler server API execution

Example Code:

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

Documentation Notes:

The php_sapi_name() function documentation provides further information:

  • Possible Return Values: While not exhaustive, the function may return values such as "apache," "cgi," "nsapi," and "tux," representing different server APIs.
  • PHP >= 4.2.0: PHP introduced a predefined constant, PHP_SAPI, which holds the same value as php_sapi_name().

The above is the detailed content of How to Determine if a PHP Script is Running on 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