How to distinguish command-line and web-server invocation? [duplicate]

浪子不回头ぞ 提交于 2019-11-28 16:03:34

If called from command line, the server variable HTTP_USER_AGENT is not set. I use this constant to define, whether the script is called from command line or not:

define("CLI", !isset($_SERVER['HTTP_USER_AGENT']));

UPDATE: Since this answer is still marked as the 'correct' one, I'd like to revise my statement - relying on the "User-Agent" header can be problematic, since it's a user-defined value.

Please use php_sapi_name() == 'cli' or PHP_SAPI == 'cli', as suggested by Eugene/cam8001 in the comments.

Thanks for pointing this out!

I've compared the $_SERVER superglobal in both invocations. It seems that $_SERVER['argc'] (i.e. number of arguments passed to the script) is only set when running from shell/command line:

<?php
if (isset($_SERVER['argc'])) {
    define('CLI', true);
} else {
    define('CLI', false);
}

That seems to work both on Linux and Windows hosts. (First I thought about checking for some of the environment variables, but those are different for every operating system. Also, all the $_SERVER['HTTP_*'] headers are missing in the CLI version, but I'm not sure if that's reliable enough.)

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