1

Possible Duplicate:
What is the canonical way to determine commandline vs. http execution of a PHP script?

I sometimes run php scripts from command line. Either with cron or other one time scripts.

I would like to know if its possible within the php script to determine if its being run via command line?

<?php

$isRunFromCommandLine = // set to (true:false) -- not sure how to do this

if($isRunFromCommandLine){
  echo 'You are running from command line';
}
else{
  echo 'You are not running php via command line'
}

?>
Community
  • 1
  • 1
Robbo_UK
  • 11,351
  • 25
  • 81
  • 117
  • You are right, it is duplicated. My initial search did not find it. I dont think its titled very well? thanks for the link +1. – Robbo_UK Jul 04 '12 at 11:02

2 Answers2

1

I would like to know if its possible within the php script to determine if its being run via command line?

Definitely. Check for the output of php_sapi_name( ), it will tell you whether or not you're running in CLI mode.

$cli = php_sapi_name( ) === 'cli';
var_dump( $cli );
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • I suggest this is NOT the best way, see the docs on php_sapi_name() and you'll see it can vary widely. The Magento `Mage_Shell_Abstract` class uses the variable: `$_SERVER['REQUEST_METHOD']` - if present, the script is being run in a browser, otherwise it's a CLI. – Oliver Williams Jan 12 '17 at 23:48
1

if the script is running via browse the variable $_SERVER['HTTP_USER_AGENT'] will set and if it's vai terminal it will not set

if(isset($_SERVER['HTTP_USER_AGENT'])){
   echo "Via browse";
}
else{
   echo "Via terminal";
} 
Miqdad Ali
  • 6,129
  • 7
  • 31
  • 50