How do I detect if PHP is running on a command line or server?

Asked

Viewed 1,791 times

3

Sometimes, when I run a 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?

  • Check if PHP is running and the version: php --version

  • @Antonioalexandre See the PHP version I already know :p. The question is whether it is running on the command line or not...

2 answers

7


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

The PHP documentation says:

string php_sapi_name(void)

Returns a lowercase string describing 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 
}

5

You can do this by checking the value of the constant PHP_SAPI.

If it is "cli", 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 function php_sapi_name may vary according to the server. For example, when running in Apache2, the value returned will be "apache2handler", if you use the built-in server PHP, the value returned is "cli-server". But the value returned when using on the command line is always "cli".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.