How to Expand Short URLs To Original URL Using PHP and cURL
Hello guyz today I am going to write a tutorial on short URLs, there are many URL shortening services available and you don’t know where your browser is taking you by clicking that URL and many people don’t want to open them even I am also one of them, so here I am giving you a solution where you can get original URL behind the short link without opening that page and doing this with PHP cURL and preg_replace methods.
Also Read: HTTP POST Using PHP cURL
A very easy and simple snippet that can perform this task.
PHP Snippet:
<?php function ger_origenal_url($url) { $ch = curl_init($url); curl_setopt($ch,CURLOPT_HEADER,true); // Get header information curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false); $header = curl_exec($ch); $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header)); // Parse information for($i=0;$i<count($fields);$i++) { if(strpos($fields[$i],'Location') !== false) { $url = str_replace("Location: ","",$fields[$i]); } } return $url; } ?>
How it works
Above cURL extract only header information in which we get website original location and we parsed that info and show you in output. curl_setopt($ch,CURLOPT_HEADER,true); this filed asks server to give me only your header information not the body of the in website.
Call this function:
<?php $url = "http://goo.gl/fb/37xzk"; // your short url $original_url = ger_origenal_url($url); // Calling function with short url echo "Short URL: {$url}<br/>"; // shoty URL echo "Original URL: {$original_url}"; // Original URL ?>
This will display you the original URL with short URL.
I hope this tutorial helps you please don’t forget to give us your feedback in comments.
Book: PHP Advanced and Object-Oriented Programming: Visual QuickPro Guide (3rd Edition)
Tutorial Categories:
cool, syukran
cool, syukran
SIr Curl is not working with https(ssl).