简体   繁体   中英

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;

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?

You need to use the php curl library. You can set it to follow redirects and then use the getinfo method to find our where it takes you.

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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