简体   繁体   English

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

[英]Find where URL redirects to using PHP

I am looking to find where a URL redirects to, currently I am getting a web page's information using file_get_contents() but some of the pages are returning a 301/302 header status and I want to use a function to find the url that the page redirects to; 我想找到一个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;
}

Is there any way to just find out the url of the redirect so I can then run the page_info() function on the correct URL? 有没有办法找到重定向的URL,以便我可以在正确的URL上运行page_info()函数?

You need to use the php curl library. 你需要使用php curl库。 You can set it to follow redirects and then use the getinfo method to find our where it takes you. 您可以将其设置为遵循重定向,然后使用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);
}

You can pass second parameters to the curl_getinfo method to get more specific information 您可以将第二个参数传递给curl_getinfo方法以获取更具体的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM