how to make a PHP file run-able only through CLI mode?

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.


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


See:

  • What is the canonical way to determine commandline vs. http execution of a PHP script?
  • Is there any way to know if a php script is running in cli mode?
  • PHP - what is the best & easy way to determine if the current invocation is from CLI or browser

Short story: php_sapi_name().