Home > Backend Development > PHP Tutorial > How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?

How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?

Patricia Arquette
Release: 2024-12-29 00:37:10
Original
931 people have browsed it

How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?

Distinguishing Command-Line Execution from HTTP Execution in PHP

Determining whether a PHP script is executed via the command line or HTTP request is essential for customizing output formats. While inspecting the SERVER['argc'] variable may seem like a valid approach, it's not always accurate, even with Apache's 'Apache 2.0 Handler' server API.

The canonical method to accomplish this task is the php_sapi_name() function.

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

As specified in the PHP documentation:

php_sapi_name returns the type of interface between the web server and PHP.

Possible return values include "apache2handler," "cgi," "cli," "isapi," "litespeed," etc.

Alternatively, you can use the PHP_SAPI constant, which has the same value as php_sapi_name(), introduced in PHP version 4.2.0.

The above is the detailed content of How do I Determine if a PHP Script is Executed via Command Line or HTTP Request?. 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