Home > Backend Development > PHP Tutorial > How to Determine Whether Your PHP Script is Running on the CLI or a Web Server?

How to Determine Whether Your PHP Script is Running on the CLI or a Web Server?

Patricia Arquette
Release: 2024-10-29 11:17:29
Original
235 people have browsed it

 How to Determine Whether Your PHP Script is Running on the CLI or a Web Server?

Determining PHP Invocation Type: CLI vs. Web Server

When running PHP scripts, it can be useful to know whether the invocation is from the command line interface (CLI) or a web server. This information can be leveraged to tailor the script's behavior accordingly.

php_sapi_name Function

The recommended method to determine the invocation type is to use the php_sapi_name function. This function returns a lowercase string representing the interface type. Additionally, PHP provides a constant, PHP_SAPI, which can be used in place of the function.

Function Usage:

To determine if PHP is being run from the CLI, you can use the following code snippet:

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

This function returns true if the script is being run from the CLI and false if it is being executed by a web server.

Sample Implementation:

The following code example illustrates how to utilize the php_sapi_name function:

<code class="php">if (isCommandLineInterface()) {
    // Execute CLI-specific code
} else {
    // Execute web server-specific code
}</code>
Copy after login

Additional Resources:

For more information on PHP_SAPI, refer to the following documentation:

  • http://php.net/php_sapi_name

The above is the detailed content of How to Determine Whether Your PHP Script is Running on the CLI or a Web Server?. 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