curl_getinfo函数返回有关HTTP请求结果的大量元数据.但是,由于某种原因,它不包括我想要的信息,如果请求返回HTTP重定向代码,则是目标URL.
我没有使用CURLOPT_FOLLOWLOCATION,因为我想将特定的重定向代码作为特殊情况处理.
如果cURL可以遵循重定向,为什么它不能告诉我当它没有跟随它们时它们重定向到什么?
当然,我可以设置CURLOPT_HEADER标志并选择Location标头.但是有更有效的方法吗?
您可以简单地使用它:(CURLINFO_REDIRECT_URL)
$info = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
echo $info; // the redirect URL without following it
Run Code Online (Sandbox Code Playgroud)
正如您所提到的,禁用 CURLOPT_FOLLOWLOCATION 选项(在执行之前)并在执行后放置我的代码。
CURLINFO_REDIRECT_URL - 禁用 CURLOPT_FOLLOWLOCATION 选项:在上一个事务中找到的重定向 URL,接下来应该手动请求。启用 CURLOPT_FOLLOWLOCATION 选项后:这是空的。本例中的重定向 URL 可在 CURLINFO_EFFECTIVE_URL 中找到
这可以通过4个简单的步骤完成:
步骤1.初始化卷曲
curl_init($ch); //initialise the curl handle
//COOKIESESSION is optional, use if you want to keep cookies in memory
curl_setopt($this->ch, CURLOPT_COOKIESESSION, true);
Run Code Online (Sandbox Code Playgroud)
第2步。获取标头 $url
curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
curl_setopt($ch, CURLOPT_HEADER, true); //include headers in http data
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //don't follow redirects
$http_data = curl_exec($ch); //hit the $url
$curl_info = curl_getinfo($ch);
$headers = substr($http_data, 0, $curl_info['header_size']); //split out header
Run Code Online (Sandbox Code Playgroud)
步骤3.检查您的响应码是否正确
if (!($curl_info['http_code']>299 && $curl_info['http_code']<309)) {
//return, echo, die, whatever you like
return 'Error - http code'.curl_info['http_code'].' received.';
}
Run Code Online (Sandbox Code Playgroud)
步骤4.解析标头以获取新的URL
preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!", $headers, $matches);
$url = $matches[1];
Run Code Online (Sandbox Code Playgroud)
有了新的URL后,您可以根据需要重复执行步骤2-4。
| 归档时间: |
|
| 查看次数: |
7483 次 |
| 最近记录: |