php 获取url参数headerContent-Typeapplicationjson;function getFromCache$cacheKey 连接到Redis服务器 $redis = new Redis; $redis-connect127001 6379; 从缓存中获取数据 $cachedData = $redis-get$cacheKey;
在你的代码中,你使用了file_get_contents函数来获取URL的内容。然而,当你使用curl来获取重定向后的地址时,file_get_contents函数无法获取到重定向后的内容。这就是为什么$values['var2']为空的原因。
要解决这个问题,你可以使用curl来获取URL的内容,并且在获取重定向后的地址时保存响应的头部信息。下面是修改后的geturl函数:
function geturl($url){
$ch = curl_init($url);
// 设置请求头
$headers = [
'Host: api.huoshan.com',
'Connection: keep-alive',
'Cache-Control: max-age=0',
'Upgrade-Insecure-Requests: 1',
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Sec-Fetch-Site: none',
'Sec-Fetch-Mode: navigate',
'Sec-Fetch-User: ?1',
'Sec-Fetch-Dest: document',
'sec-ch-ua: "Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"',
'sec-ch-ua-mobile: ?0',
'sec-ch-ua-platform: "Windows"',
'Accept-Encoding: gzip, deflate, br',
'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7,ga;q=0.6'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
// 获取重定向后的地址
$redirectUrl = '';
if (preg_match('/Location: (.+)/', $response, $matches)) {
$redirectUrl = trim($matches[1]);
}
curl_close($ch);
$result = array(
'var1' => $redirectUrl,
'var2' => $response
);
return $result;
}
现在,你可以使用修改后的geturl函数来获取重定向后的地址和响应的头部信息。 这样,$values['var2']将包含响应的头部信息,并且不会为空。
如果你仍然遇到问题,请检查你的URL是否正确,并确保你的服务器能够访问该URL
原文地址: https://www.cveoy.top/t/topic/ihJ8 著作权归作者所有。请勿转载和采集!