How to check with PHP if the script is being run from the console or browser request? How to check with PHP if the script is being run from the console or browser request? php php

How to check with PHP if the script is being run from the console or browser request?


Use php_sapi_name()

Returns a lowercase string thatdescribes the type of interface (theServer API, SAPI) that PHP is using.For example, in CLI PHP this stringwill be "cli" whereas with Apache itmay have several different valuesdepending on the exact SAPI used.

For example:

$isCLI = (php_sapi_name() == 'cli');

You can also use the constant PHP_SAPI


I know this is an old question, but for the record, I see HTTP requests coming in without a User-Agent header and PHP does not automatically define HTTP_USER_AGENT in this case.