判断 php 程序是通过什么方式运行的 (浏览器,还是命令行)

php 程序既可以通过浏览器来访问(一般是 apache、nginx等服务器),

也可以通过命令行来直接运行(cli 执行)

如果需要判断 当前程序是以何种方式来执行,应该怎样判断呢,使用:php_sapi_name() 方法,

示例:

<?php

    function is_cli_mode() {
        $sapi_type = php_sapi_name();
        if (isset($sapi_type) && substr($sapi_type, 0, 3) == 'cli') {
            return true;
        } else {
            return false;
        }
    }
 
    // main logic
    if (is_cli_mode()) {
        echo 'It is using cli.';
    }
    else {
        echo 'It is using other mode.';
    }

参考:http://php.net/manual/en/function.php-sapi-name.php

猜你喜欢

转载自www.cnblogs.com/tommy-huang/p/9595674.html