Home >Backend Development >PHP Tutorial >How Do I Determine If a PHP Script Is Running From the Command Line or Through HTTP?

How Do I Determine If a PHP Script Is Running From the Command Line or Through HTTP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-22 11:14:10557browse

How Do I Determine If a PHP Script Is Running From the Command Line or Through HTTP?

Determining Command-Line vs. HTTP Execution in PHP

In developing PHP scripts, it often becomes necessary to distinguish between execution via the command-line or through HTTP. Output formatting and other aspects of script behavior may differ based on this differentiation.

Canonical Method: php_sapi_name()

The recommended approach to determine the execution mode is to utilize the php_sapi_name() function. It returns the type of interface between the web server and PHP.

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

Additional Notes:

  • php_sapi_name() provides a comprehensive list of possible return values, including various web server types and command-line interfaces.
  • In PHP >= 4.2.0, PHP_SAPI is a predefined constant that has the same value as php_sapi_name().

The above is the detailed content of How Do I Determine If a PHP Script Is Running From the Command Line or Through HTTP?. 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