dongpingwu8378 2013-08-09 13:49
浏览 61
已采纳

检查接口类型是否为PHP中的CLI

It looks like there are two typical ways to determine if a script is running via command line.

  1. if ( defined('STDIN') ) # Running via CLI
  2. if (PHP_SAPI === 'cli') # Running via CLI

Since they're both used, and recommended, I assume they both work well. My question is: are there any fringe cases where one would fail? Which is preferred, and why?

  • 写回答

1条回答 默认 最新

  • dqjmq28248 2013-08-09 14:00
    关注

    I wouldn't rely on if (defined('STDIN')) ever. Simply because, if the STDIN constant isn't defined, I can define it myself:

    defined('STDIN') || define('STDIN', 'random value');
    

    that would have any of the following code, using if (defined('STDIN')) believing it's running on the command line, whereas PHP_SAPI will always be defined.
    Another thing you have to take into account is namespaces. Sure, this affects both checks, but you could also use the php_sapi_name function to be sure, or simply:

    if (\PHP_SAPI === 'cli')
    

    Which, to my eye, is more readable than:

    if (defined('\\STDIN'))
    

    So basically, use any of the three options, but be aware that STDIN can be a user-defined constant, too. PHP_SAPI or the return value of php_sapi_name is always going to be astring (AFAIK), and you know what value to expect when running a CLI script: 'cli'. Though, if for some reason you don't trust that, I have seen people do this:

    if (stristr(PHP_SAPI, 'cli') && strpos(PHP_SAPI, 'cli') === 0)
    

    But that's just paranoid, IMHO.
    Some just check $argv, but that implies the register_argc_argv setting is enabled, which it is by default, but it can be disabled, which you could, in turn, counter with something like:

    #!/var/bin/php -n
    <?php
        if (!is_array($argv))
        {
            exit();
        }
    

    by using /path/to/php -n, you're not using any ini file, so default settings will be used, and the since the default setting for register_argc_argv is 1, $argv will be available.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c