PHP: Detect if Script is Running from Console
I hacked together a script to import a large amount of data from a CSV file that was not very fun to work with, and I felt the need to restrict access to the command line in case there was any extra overhead in the script, or anything unforeseen quirks from running such an intensive script in the browser. (I didn’t really have to restrict access as I removed the import script after it was run, but now I needed to know.) Somehow, I needed to capture information about exactly HOW the script was being executed. It’s actually quite simple, PHP captures your console environment into a $_SERVER variable, specifically $_SERVER['CONSOLE'] and/or $_SERVER['TERM'].
if(!isset($_SERVER['SHELL'])) { echo "Please run this script from the console."; exit; }
[Edit: Shortly after posting the above snippet, I found a PHP function (see: php_sapi_name) that returns the type of interface between the web server and PHP. In this case, we are looking for it to return the value 'cli' for command line interface.]
if(php_sapi_name() != 'cli') { echo "Please run this script from the console."; exit; }



