curl doesn't seem to have a function or option to get the redirect target; it can be extracted using various methods:
From the answer :
Apache can respond with an HTML page in case of a 301 redirect (it seems that this is not the case with the 302nd).
If the answer has a format similar to:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>301 Moved Permanently</title> </head><body> <h1>Moved Permanently</h1> <p>The document has moved <a href="http://www.xxx.yyy/zzz">here</a>.</p> <hr> <address>Apache/2.2.16 (Debian) Server at www.xxx.yyy Port 80</address> </body></html>
You can extract the redirect URL using DOMXPath :
$i = 0; foreach($urls as $url) { if(substr($url,0,4) == "http") { $c = curl_init($url); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); $result = @curl_exec($c); $status = curl_getinfo($c,CURLINFO_HTTP_CODE); curl_close($c); $results[$i]['code'] = $status; $results[$i]['url'] = $url; if($status === 301) { $xml = new DOMDocument(); $xml->loadHTML($result); $xpath = new DOMXPath($xml); $href = $xpath->query("//*[@href]")->item(0); $results[$i]['target'] = $href->attributes->getNamedItem('href')->nodeValue; } $i++; } }
Using CURLOPT_NOBODY
However, there is a faster way, as @ gAMBOOKa points out; Using CURLOPT_NOBODY . This approach simply sends a HEAD request instead of a GET (without loading the actual content, so it should be faster and more efficient) and saves the response header.
Using a regular expression, the destination URL can be extracted from the header:
foreach($urls as $url) { if(substr($url,0,4) == "http") { $c = curl_init($url); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_NOBODY,true); curl_setopt($c, CURLOPT_HEADER, true); $result = @curl_exec($c); $status = curl_getinfo($c,CURLINFO_HTTP_CODE); curl_close($c); $results[$i]['code'] = $status; $results[$i]['url'] = $url; if($status === 301 || $status === 302) { preg_match("@https?://([-\w\.]+)+(:\d+)?(/([\w/_\-\.]*(\?\S+)?)?) ?@ ",$result,$m); $results[$i]['target'] = $m[0]; } $i++; } }
Rem.co
source share