Several months ago I created a site called LinkUnshorten with the goal to guard people against short links from sites like goo.gl, bit.ly, tinyurl etc. Url shorteners are great but they do have the risk of redirecting you to a site you may not want to visit. LinkUnshorten solves this issue by expanding short links to show you the final redirect URL. I also made a chrome extension that will detect short links.
LinkUnshorten is written in Laravel, a php framework and uses CURL to follow any url to its final destination. I wanted to share a code snippet on how the site finds the final url.
$ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $SHORT_URL_HERE); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $redirectUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch);
The key here is to use CURLOPT_FOLLOWLOCATION, which will follow any “Location: ” header that the server sends as part of the HTTP header. So even if the short url uses multiple url shorteners, it will continue to search for the final destination url.
Please leave a comment below if you have any questions or feedback.