使用 PHP 查找 URL 重定向到的位置


Find where URL redirects to using PHP

我正在寻找URL重定向到的位置,目前我正在使用file_get_contents()获取网页的信息,但某些页面返回301/302标头状态,我想使用一个函数来查找页面重定向到的URL;

function page_info($url) {
$fp = file_get_contents($url);
$title = preg_match("/<title>(.*)<'/title>/siU", $fp, $title_matches);
$h1 = preg_match("/<h1>(.*)<'/h1>/siU", $fp, $h1_matches);
$h2 = preg_match("/<h2>(.*)<'/h2>/siU", $fp, $h2_matches);
$meta_desc = get_meta_tags($url);
$data = array("title"=>trim(preg_replace('/'s+/', ' ', $title_matches[1])), "metadesc" => $meta_desc['description'],"h1"=>trim(preg_replace('/'s+/', ' ', $h1_matches[1])), "h2"=>trim(preg_replace('/'s+/', ' ', $h2_matches[1])));
return $data;
}

有没有办法找出重定向的网址,这样我就可以在正确的网址上运行page_info()函数?

你需要使用 php curl 库。您可以将其设置为遵循重定向,然后使用 getinfo 方法找到我们的 带您去的地方。

$curl = curl_init('http://example.org/someredirect');
curl_setopt($curl, CURLOPT_POSTFIELDS, "foo");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_exec($curl);
if(!curl_errno($curl))
{
     $info = curl_getinfo($curl);
}

可以将第二个参数传递给 curl_getinfo 方法以获取更具体的信息