EdanB
EdanB

Reputation: 1496

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

I tried things like $_ENV['CLIENTNAME'] == 'Console' but that seems to work on only certain OS's (worked in windows, not linux).

I tried !empty($_ENV['SHELL']) but that doesn't work always either...

Is there a way to check this that will work in all OS's/environments?

Upvotes: 54

Views: 28538

Answers (6)

Tom Haigh
Tom Haigh

Reputation: 57845

Use php_sapi_name()

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

For example:

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

You can also use the constant PHP_SAPI

Upvotes: 94

Ganesh Kandu
Ganesh Kandu

Reputation: 631

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

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

Upvotes: 18

SteveK
SteveK

Reputation: 1006

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.

Upvotes: 3

Andrea Mauro
Andrea Mauro

Reputation: 842

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

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

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

Upvotes: 2

Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36853

One solution is to check whether STDIN is defined:

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

Upvotes: 1

J-16 SDiZ
J-16 SDiZ

Reputation: 26930

Check the HTTP_USER_AGENT , it should exist in http request

Upvotes: -2

Related Questions