May 12, 2014 10:49 am

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.

How to Expand Short URLs To Original URL Using PHP and cURL

[wpdm_file id=102]DEMO

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.

[wpdm_file id=102]DEMO

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)

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

3 responses to “How to Expand Short URLs To Original URL Using PHP and cURL”

  1. MatJengkol says:

    cool, syukran

  2. MatJengkol says:

    cool, syukran

  3. Mohd Farhan Rizwan says:

    SIr Curl is not working with https(ssl).

Leave a Reply

Your email address will not be published. Required fields are marked *