【发布时间】:2022-01-02 06:47:07
【问题描述】:
一些已经运行了几个月的代码突然不工作了。我已将其范围缩小到 PHP file_get_contents 部分。以下是代码片段:
// This upper portion was added to send a user-agent with the request
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n",
],
];
$context = stream_context_create($opts);
// End of the added part except for the actual get-file-contents request line
$ViewLat = 40.7;
$ViewLng = -73.9;
$Distance = 1000;
$input1 = "https://api.helium.io/v1/hotspots/location/distance?lat=40.7&lon=-73.9&distance=1000";
$input2 = "https://api.helium.io/v1/hotspots/location/distance/?lat=$ViewLat&lon=$ViewLng&distance=$Distance";
$json_string = file_get_contents(urlencode($input2), false, $context); // added the last 2 arguments
var_dump($ViewLat);
echo "<br>";
var_dump($ViewLng);
echo "<br>";
var_dump($Distance);
echo "<br>";
var_dump($input1);
echo "<br>";
var_dump($json_string);
无论我使用 $input1 还是 $input2,它们都在 var_dump 输出中返回 bool(false)。但是如果你把字符串直接放到浏览器中,它会返回一个数据数组。
这段代码在 8 月/9 月可以正常工作,但现在不行了。
这里是 var_dump 输出:
float(40.7)
float(-73.9)
int(1000)
string(84) "https://api.helium.io/v1/hotspots/location/distance?lat=40.7&lon=-73.9&distance=1000"
bool(false)
【问题讨论】:
-
可能检测到这是一个自动请求并阻止它。您是否尝试在邮递员中发送请求?
-
阅读stackoverflow.com/questions/1975461/… 看看是否有帮助。
-
urlencode 弄乱了您的 URL。
var_dump(urlencode($input2))你会明白我的意思。 -
但是,如果不对其进行编码,它仍然无法与
file_get_contents一起使用。我试了一下,得到了failed to open stream: HTTP request failed! HTTP/1.1 429 Slow down gun powder!,这意味着它被主机阻止了太多的请求。 -
我刚刚尝试了问题 1975461 中的一些建议,但没有任何效果。我正在查看我的 php.ini 文件以查看有哪些设置,但我使用此命令访问其他 API 没有任何问题。我不确定如何发送模拟浏览器请求的标头。
标签: php api file-get-contents