[ACCEPTED]-How to check with PHP if the script is being run from the console or browser request?-command-line-interface

Accepted answer
Score: 90

Use php_sapi_name()

Returns a lowercase string that describes 6 the type of interface (the Server API, SAPI) that 5 PHP is using. For example, in CLI PHP 4 this string will be "cli" whereas 3 with Apache it may have several different 2 values depending on the exact SAPI used.

For 1 example:

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

You can also use the constant PHP_SAPI

Score: 15

Check on http://php.net/manual/en/features.commandline.php#105568 "PHP_SAPI" Constant

<?php
if (PHP_SAPI === 'cli')
{
   // ...
}
?> 

0

Score: 3

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

Score: 2
if ($argc > 0) {
    // Command line was used
} else {
    // Browser was used
}

$argc coounts the amount of arguments passed 3 to the command line. Simply using php page.php, $argc 2 will return 1

Calling page.php with a browser, $argc 1 will return NULL

Score: 1

One solution is to check whether STDIN is 1 defined:

if (!defined("STDIN")) {
    die("Please run me from the console - not from a web-browser!");
}

More Related questions