16

It's available to browser,

but I don't want it to execute when browsed by user,

say,when browsed should exit,

is there a way to detect whether it's currently Cmmand Line Mode?

omg
  • 136,412
  • 142
  • 288
  • 348

4 Answers4

11

Here is what i'm using, for a long time now... (since php 4 iirc)

(PHP_SAPI !== 'cli' || isset($_SERVER['HTTP_USER_AGENT'])) && die('cli only');

to be used as first line of the php script.

Florian F
  • 4,044
  • 3
  • 30
  • 31
2

Here is a trick:

You can check for the $argc/$argv parameters which are always available in CLI mode.

#!/usr/bin/php
<?php 

ini_set('register_argc_argv', 0);  

if (!isset($argc) || is_null($argc))
{ 
    echo 'Not CLI mode';
} else {
    echo 'CLI mode';
}

register_argc_argv

$argc

Boris Guéry
  • 47,316
  • 8
  • 52
  • 87
  • 3
    Why fiddle with INI settings when php_sapi_name() is designed for exactly this purpose? – Ben Blank Jun 03 '09 at 00:07
  • There is another problem,use this way,when debugging in Zend,it's also treated as "Not CLI mode" even when it is actually – omg Jun 03 '09 at 00:10
2

Another trick, $_SERVER has variables that are only set in CLI mode.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
1
if (!defined('STDIN')) {
    // accessed through the web browser
    die();
}

I use this when creating PHP CLI scripts. Works very well.

Zankar
  • 249
  • 4
  • 5