How to differentiate between http and cli requests?

六月ゝ 毕业季﹏ 提交于 2019-11-28 03:10:08

问题


The title is quiet straightforward. I have to know on server side if the script called through HTTP request or by command line. I could examine the $_SERVER['argv'] or $_SERVER['argc'].
What is the pragmatic way to do that?


回答1:


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

<?php
echo PHP_SAPI;
echo php_sapi_name();
?>



回答2:


Look at the keys in $_SERVER. If it is a cli request, you shouldn't see any that start with "HTTP".


Here is some simple test code:

<?php

foreach( $_SERVER as $k=>$v ){
    echo "$k: $v\n";
}

?>

And here is the output:

aj@mmdev0:~/so$ php cli.php |grep HTTP
aj@mmdev0:~/so$



回答3:


Possibly checking if no $_SERVER['HTTP_HOST'] is set? Because I believe that variable is populated through the Request Headers sent to a file on exection, and the command line probably doesn't send headers.




回答4:


You can check if the global variable $argc is set.




回答5:


I suggest checking if(isset($_SERVER['SERVER_NAME']))




回答6:


But you have to send the data through http (tcp) anyway no matter if the script is called from cli or from a browser



来源:https://stackoverflow.com/questions/2172970/how-to-differentiate-between-http-and-cli-requests

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