Get final redirect with Curl PHP

2019-07-13 23:25发布

I have to get the final redirect url from the this: https://web.archive.org/web/20070701005218/http://www.maladnews.com/ which actually redirects to this: https://web.archive.org/web/20080109064420/http://www.maladnews.com/Site%203/Malad%20City%20&%20Oneida%20County%20News/Malad%20City%20&%20Oneida%20County%20News.html

I tried the answers from other stackoverflow answers which works for other websites but not for the above link.

I've tried to extract regular location header:

if(preg_match('#Location: (.*)#', $html, $m))
 $l = trim($m[1]);

and also checked the javascript way:

preg_match("/window\.location\.replace\('(.*?)'\)/", $html, $m) ? $m[1] : null;

Please help!

1条回答
We Are One
2楼-- · 2019-07-13 23:49

Use curl_getinfo() with CURLINFO_REDIRECT_URL or CURLINFO_EFFECTIVE_URL depending on your use case.

CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL

-- http://php.net/manual/en/function.curl-getinfo.php

Example:

<?php
$url = 'https://google.com/';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$html = curl_exec($ch);

$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

curl_close($ch);

echo "Original URL:   " . $url . "\n";
echo "Redirected URL: " . $redirectedUrl . "\n";

When I run this code, the output is:

Original URL:   https://google.com/
Redirected URL: https://www.google.com/
查看更多
登录 后发表回答