How to differentiate between http and cli requests

2019-01-26 06:39发布

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?

6条回答
走好不送
2楼-- · 2019-01-26 07:17

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-26 07:26

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$
查看更多
够拽才男人
4楼-- · 2019-01-26 07:28

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

<?php
echo PHP_SAPI;
echo php_sapi_name();
?>
查看更多
叛逆
5楼-- · 2019-01-26 07:28

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

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-26 07:33

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.

查看更多
唯我独甜
7楼-- · 2019-01-26 07:37

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

查看更多
登录 后发表回答