我知道当我将CURLOPT_FOLLOWLOCATION设置为true时,cURL将跟随Location标头并重定向到新页面。但是有可能只获得新页面的标题而不实际重定向吗?还是不可能?
不需要。您必须禁用FOLLOWLOCATION
,从响应中提取重定向URL,然后使用该URL发出新的HEAD请求。
似乎是PHP cURL: Get target of redirect, without following it的副本
但是,这可以通过3个简单的步骤完成:
步骤1.初始化卷曲
curl_init($ch); //initialise the curl handle
//COOKIESESSION is optional, use if you want to keep cookies in memory
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
第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
步骤3.解析标头以获取新URL
preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!", $headers, $matches);
$url = $matches[1];
获得新网址后,您可以随时重复步骤2-3。
将CURLOPT_FOLLOWLOCATION
设为false
,将CURLOPT_HEADER
设为true
,并从响应标题中获取“Location”。
对于分析标题,您可以使用CURLOPT_HEADERFUNCTION
确保将CURLOPT_HEADER
设置为True以获取响应中的标头,否则响应将返回为空字符串
是的,您可以将其设置为遵循重定向,直到您获得标头响应的最后一个位置。
获取最后一次重定向的函数:
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_setopt($ch,CURLOPT_HEADER,false); // if you want to print the header response change false to true
$response = curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target; // the location you want
return false;
}