How to detect if PHP is running on command line or server?

3

Sometimes, when I run some PHP script, I need to know if it is running on the command line or not, because if it is running on the command line, I can perform a different action.

Is there any way to detect if the script is running on the command line or if it is running on a server?

    
asked by anonymous 19.01.2017 / 11:42

2 answers

7

Use the function php_sapi_name() , if the return is "cli" , is running on the line command.

The PHP documentation says:

string php_sapi_name(void)
     

Returns a lowercase string that describes the type of interface between the web server and PHP (Server API, SAPI). In CGI PHP, this string is "cgi", in mod_php for Apache, this string is "apache" and so on.

Example:

if (php_sapi_name() == "cli") {
    // Executando na linha de comando
} else {
    // Executando no servidor 
}
    
19.01.2017 / 11:46
5

You can do this by checking the value of PHP_SAPI .

If it is "cli" , it is running on the command line.

Example:

if (PHP_SAPI === 'cli') {
     // Está na linha de comando
} else {
    // Está rodando no via servidor 
}

Note : When the script is running on a server, the values returned by the constant PHP_SAPI or the php_sapi_name function may vary depending on the server. For example, when running on Apache2, the returned value will be "apache2handler" , if you use PHP's built-in server , the returned value is "cli-server" . But the value returned when using the command line is always "cli" .

    
19.01.2017 / 11:48