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

时间:2018-04-27 12:58:37

标签: php curl get-headers

以下是网址: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的服务器端还是别的什么样的安装功能很差?

2 个答案:

答案 0 :(得分:4)

这是因为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

答案 1 :(得分:0)

只需使用php curl函数:

function getMyHeaders($url)
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,    
        CURLOPT_HEADER         => true,    
        CURLOPT_FOLLOWLOCATION => true,    
        CURLOPT_USERAGENT      => "spider",
        CURLOPT_AUTOREFERER    => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_NOBODY => true
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}
print_r(getMyHeaders('https://www.grammarly.com'));
相关问题