THE PROBLEM
我正在管理一个网页,它运行在server hosted by Inmotion和使用PHP 7.2.34.让我们称它为"https://company-website.net/"
在该页面中,我们需要读取一个JSON文件.文件肯定在那里,用户可以打开URL并打开它,json文件位于"https://company-website.net/locale.json""中
从一天到另一天,在January 10th 2024,file_get_contents suddenly returned this php error:
FILE_GET_CONTENTS(https://company-website.net/locale.json):无法打开流:HTTP请求失败!HTTP/1.1 406不可接受
代码看起来像这样:
$fileUrl = 'https://'.$_SERVER['SERVER_NAME'].'/locale.json';
$file = file_get_contents($fileUrl);
I tried something else
我try 设置一个Accept标头,就像它在这个堆栈溢出线程上所说的那样(刚刚将Accept-Language:EN更改为Accept:/: PHP file_get_contents() and setting request headers个
因此,代码的结尾如下:
$fileUrl = 'https://'.$_SERVER['SERVER_NAME'].'/locale.json';
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept: */*"
]
];
$context = stream_context_create($opts);
$file = file_get_contents($fileUrl, false, $context);
但什么都没有
THE SOLUTION IN THE END
然后,我最终更改了curl的文件获取内容,如下面的帖子所述: PHP file_get_contents() returns "failed to open stream: HTTP request failed!"个
结果是这样的:
$fileUrl = 'https://'.$_SERVER['SERVER_NAME'].'/locale.json';
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $fileUrl);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Company Name');
$file = curl_exec($curl_handle);
curl_close($curl_handle);
AND IT WORKED.
但我仍然感到困惑的是,为什么它会从一天到另一天停止工作,不确定它是否与PHP的弃用有关,InMotion改变了一些安全方面的东西,真的迷失在这里.我仍然希望try 使用FILE_GET_CONTENTS,并了解问题可能是什么.如果有人能给出任何见解,我将非常感激.