In PHP, how to detect the execution is from CLI mode or through browser ? [duplicate]

Solution 1:

Use the php_sapi_name() function.

if (php_sapi_name() == "cli") {
    // In cli-mode
} else {
    // Not in cli-mode
}

Here are some relevant notes from the docs:

php_sapi_name — Returns the type of interface between web server and PHP

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

Solution 2:

if(php_sapi_name() == "cli") {
    //In cli-mode
} else {
    //Not in cli-mode
}

Solution 3:

There is a constant PHP_SAPI has the same value as php_sapi_name().

(available in PHP >= 4.2.0)

Solution 4:

I think you can see it from the $_SERVER variables. Try to print out the $_SERVER array for both browser & CLI and you should see differences.