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

 ̄綄美尐妖づ 提交于 2019-11-29 18:27:11

问题


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?


回答1:


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().




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/942435/how-to-make-a-php-file-run-able-only-through-cli-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!