Detect the execution is from CLI mode in PHP

PHP Jun 05, 2020 Viewed 17 Comments 0

In PHP, there are two ways to determine if the current invocation is from CLI.

  • With php_sapi_name method

php_sapi_name returns the interface type, as a lowercase string. 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, fpm-fcgi, isapi, litespeed, milter, nsapi, phpdbg, phttpd, pi3web, roxen, thttpd, tux, and webjames.

if(php_sapi_name() == "cli") {
    // In cli-mode
} else {
    // Not in cli-mode
}
  • With PHP_SAPI Predefined Constants

PHP_SAPI is the same as php_sapi_name.

if(PHP_SAPI == "cli") {
    // In cli-mode
} else {
    // Not in cli-mode
}
Updated Jun 05, 2020