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;
}

Mainden Post

Hello – welcome to my blog. Yes, this is the first post of the blog since the new site was setup. But don’t worry I will be posting new stuff soon on here. So keep looking at this space for some exciting stuff.

As you may already be aware that I am an experienced developer and currently working at Virgin Media. I have working with some interesting technology stack previously and therefore, I will be writing about them here in my blog.

State of the art technology stack is the key to any business’s success and being a developer my first priority is to keep myself updated about the latest trends in the market and implement them where appropriate. I am sure you will learn something as I keep writing about my experiences.

So stay tuned until then and I will be back with some brand new post soon.