What is the canonical way to determine commandline vs. http execution of a PHP script?

Bobby Jack picture Bobby Jack · Oct 6, 2008 · Viewed 40.8k times · Source

I have a PHP script that needs to determine if it's been executed via the command-line or via HTTP, primarily for output-formatting purposes. What's the canonical way of doing this? I had thought it was to inspect SERVER['argc'], but it turns out this is populated, even when using the 'Apache 2.0 Handler' server API.

Answer

user3850 picture user3850 · Oct 6, 2008

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.

In PHP >= 4.2.0, there is also a predefined constant, PHP_SAPI, that has the same value as php_sapi_name().