Hec*_*tor 5 php curl http file-get-contents php-curl
我有一个简单的 PHP 脚本,它向外部 API 发送带有一些参数的 GET 请求,并接收一些 json 数据作为响应。
我用过file_get_contents这个,它在过去几个月里有效。
例子:
$url = 'https://example.com?param1=xxx¶m2=yyy';
$data = file_get_contents($url);
Run Code Online (Sandbox Code Playgroud)
突然它停止工作,出现以下错误:
failed to open Stream: HTTP request failed!
HTTP1/1 426 Upgrade Required
Run Code Online (Sandbox Code Playgroud)
我用它替换了它cURL并且它起作用了:
function curlGet($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
file_get_contents?我认为我服务器上的任何内容都没有改变。我也在本地测试了它,它有相同的问题/解决方案,所以我猜测外部服务器/API 发生了一些变化。
我正在使用 PHP7。
什么会导致这种行为?
运行服务器的人升级了他们的软件。
这两种方法到底有什么区别?
一种是使用curl库,另一种是一些基于自定义php-core的方法。
我应该总是使用curl吗?
取决于您的用例。卷曲更加灵活。您应该使用 Guzzle(一个 http 客户端库)之类的东西。
使用 file_get_contents 时有没有办法防止这个问题?
或许。
$file = file_get_contents(
'http://www.example.com/',
false,
stream_context_create(
[ 'http'=> ['method'=>"GET"]],
['protocol_version' => '1.1' ])
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
308 次 |
| 最近记录: |