PHP – how to best determine if the current invocation is from CLI or web server

PHP

I need to determine whether the current invocation of PHP is from the command line (CLI) or from the web server (in my case, Apache with mod_php).

Any recommended methods?

Best Answer

php_sapi_name is the function you will want to use as it returns a lowercase string of the interface type. In addition, there is the PHP constant PHP_SAPI.

Documentation can be found here: http://php.net/php_sapi_name

For example, to determine if PHP is being run from the CLI, you could use this function:

function isCommandLineInterface()
{
    return (php_sapi_name() === 'cli');
}