为何get_headers()返回400 Bad Request,而CLI curl返回200 OK?
为什么PHP的get_headers()请求Grammarly返回400,而curl却返回200?
我来帮你分析这个问题——我之前也遇到过类似的情况,PHP的get_headers()和curl返回不同状态码,核心原因是两者发送的请求头不一样。
你用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/却能拿到200 OK的响应,这是因为:
get_headers()默认发送的请求头非常简陋,甚至可能缺少关键的User-Agent字段,或者使用PHP自带的标识(比如PHP/7.x.x),很多网站的反爬机制会直接拒绝这种脚本化的请求。- curl命令行工具默认会自动添加标准的浏览器风格请求头,所以能顺利通过网站的验证。
解决办法:给get_headers()添加自定义请求头
我们可以用stream_context_create()创建一个包含模拟浏览器请求头的上下文,传给get_headers(),让它发送更接近真实浏览器的请求:
// 创建包含自定义请求头的上下文 $context = stream_context_create([ 'http' => [ 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n" ] ]); // 带着上下文请求头获取响应头 $headers = get_headers('https://www.grammarly.com', 0, $context); // 打印结果 print_r($headers);
这样修改后,get_headers()发送的请求就会带上浏览器风格的User-Agent,应该就能拿到200 OK的响应头了。如果还是不行,你可以尝试添加更多常见请求头,比如Accept:
$context = stream_context_create([ 'http' => [ 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n" . "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\n" ] ]);
内容的提问来源于stack exchange,提问作者Limon Monte
相关产品推荐
相关产品推荐

