Home  >  Article  >  Backend Development  >  How do I Determine if a PHP Script is Running from the CLI or a Web Server?

How do I Determine if a PHP Script is Running from the CLI or a Web Server?

DDD
DDDOriginal
2024-10-28 09:59:02112browse

How do I Determine if a PHP Script is Running from the CLI or a Web Server?

Determining PHP Invocation Source: CLI vs Web Server

Determining whether a PHP script is executed from the command-line interface (CLI) or a web server, such as Apache with mod_php, is essential for managing your scripts accordingly.

To effectively assess the invocation source, utilize the php_sapi_name() function. It returns a lowercase string specifying the interface type. Additionally, consider using the PHP_SAPI constant for this purpose.

For instance, to discern if PHP operates within the CLI, employ the following function:

<code class="php">function isCommandLineInterface()
{
    return (php_sapi_name() === 'cli');
}</code>

This approach provides a reliable method to determine the origin of your PHP script, allowing you to adapt its execution appropriately.

The above is the detailed content of How do I Determine if a PHP Script is Running from the CLI or a Web Server?. 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