Check if script is running in CLI

There may be number of occasions when you want to check if the script is running on Command Line Interface (CLI) or the browser an you may have come across various solutions that work on one occasion but not other.

I have come across one solution that would consider various factors to decide if it is running on CLI.

function is_cli()
{
    if ( defined('STDIN') )
    {
        return true;
    }

    if ( php_sapi_name() === 'cli' )
    {
        return true;
    }

    if ( array_key_exists('SHELL', $_ENV) ) {
        return true;
    }

    if ( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) 
    {
        return true;
    } 

    if ( !array_key_exists('REQUEST_METHOD', $_SERVER) )
    {
        return true;
    }

    return false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *