Tim Habersack

Where I put my things..

How to get the final url after redirects

Nov 14th 2016

Sometimes, you have a link. And you want to save the actual, final url that link points to. A great example of this is trying to archive something on twitter. You'll want to store final urls for ones that are tweeted, not their url shortened one.

Anyway, I wrote this really quick in PHP and it works!


$d['initial_url'] = 'https://t.co/NOKpf0iHpR';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $d['initial_url']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $d['initial_url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
$d['final_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
print_r($d);

This outputs:

Array
(
    [initial_url] => https://t.co/NOKpf0iHpR
    [final_url] => https://tim.hithlonde.com/2016/announcing-js-space/
)