51

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
EdanB
  • 1,456
  • 3
  • 15
  • 15
  • Dupe http://stackoverflow.com/questions/607373/is-there-any-way-to-know-if-a-php-script-is-running-in-cli-mode – Mike B Jun 25 '09 at 09:09

6 Answers6

91

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

Tom Haigh
  • 57,217
  • 21
  • 114
  • 142
15

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

<?php
if (PHP_SAPI === 'cli')
{
   // ...
}
?> 
Ganesh Kandu
  • 601
  • 5
  • 15
3

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.

SteveK
  • 996
  • 1
  • 8
  • 11
  • It's already been mentioned in a comment bellow, you can't rely on HTTP_USER_AGENT as it's an optional header. – Nick Zinger Feb 10 '16 at 14:09
  • Did you downvote my answer and then leave a comment saying the exact same thing I said, Nick? Nice. My point, 5 years ago when I left this comment, was to tell the OP that HTTP_USER_AGENT is not reliable. – SteveK Feb 12 '16 at 03:03
  • Oh wow, obviously I misread it. Reminder not to browse SO while sleepy. Could you please edit your answer a bit so that I can change my vote? Sorry about that. – Nick Zinger Feb 12 '16 at 11:06
2
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

Andrea Mauro
  • 773
  • 1
  • 8
  • 14
1

One solution is to check whether STDIN is defined:

if (!defined("STDIN")) {
    die("Please run me from the console - not from a web-browser!");
}
Erel Segal-Halevi
  • 33,955
  • 36
  • 114
  • 183
-2

Check the HTTP_USER_AGENT , it should exist in http request

J-16 SDiZ
  • 26,473
  • 4
  • 65
  • 84