How can I get the destination URL using cURL?
$ch = curl_init($url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to follow it.$response = curl_exec($ch);preg_match_all('/^Location:(.*)$/mi', $response, $matches);curl_close($ch);echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';
A bit dated of a response but wanted to show a full working example, some of the solutions out there are pieces:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); //set url curl_setopt($ch, CURLOPT_HEADER, true); //get header curl_setopt($ch, CURLOPT_NOBODY, true); //do not include response body curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //do not show in browser the response curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //follow any redirects curl_exec($ch); $new_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); //extract the url from the header response curl_close($ch);
This works with any redirects such as 301 or 302, however on 404's it will just return the original url requested (since it wasn't found). This can be used to update or remove links from your site. This was my need anyway.