编程语言
首页 > 编程语言> > php – 为什么get_headers()返回400 Bad请求,而CLI curl返回200 OK?

php – 为什么get_headers()返回400 Bad请求,而CLI curl返回200 OK?

作者:互联网

这是URL:https://www.grammarly.com

我正在尝试使用本机get_headers()函数获取HTTP标头:

$headers = get_headers('https://www.grammarly.com')

结果是

HTTP/1.1 400 Bad Request
Date: Fri, 27 Apr 2018 12:32:34 GMT
Content-Type: text/plain; charset=UTF-8
Content-Length: 52
Connection: close

但是,如果我使用curl命令行工具执行相同操作,结果将会有所不同:

curl -sI https://www.grammarly.com/

HTTP/1.1 200 OK
Date: Fri, 27 Apr 2018 12:54:47 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 25130
Connection: keep-alive

这种反应差异的原因是什么?在Grammarly的服务器端或其他什么地方,它是否是某种糟糕的安全功能?

解决方法:

这是因为get_headers()使用默认的流上下文,这基本上意味着几乎没有HTTP头发送到URL,大多数远程服务器都会挑剔.通常,最可能导致问题的缺失标头是User-Agent.您可以在使用stream_context_set_default调用get_headers()之前手动设置它.这是一个适合我的示例:

$headers = get_headers('https://www.grammarly.com');

print_r($headers);

// has [0] => HTTP/1.1 400 Bad Request

stream_context_set_default(
    array(
        'http' => array(
            'user_agent'=>"php/testing"
        ),
    )
);

$headers = get_headers('https://www.grammarly.com');

print_r($headers);

// has [0] => HTTP/1.1 200 OK

标签:php,curl,get-headers
来源: https://codeday.me/bug/20190622/1262543.html