Home >Backend Development >PHP Tutorial >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>
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>
Additional Resources:
For more information on PHP_SAPI, refer to the following documentation:
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!