expanding short url to original url using PHP and CURL


/ Published in: PHP
Save to your folder(s)

there are numbers of url shortening services available these days, including the good old tinyurl and something really short like u.nu. now when you get the short url shortened by using any of these services, you dont know where your browser is taking you! so if you are interested to figure out the original url hiding behind these short url, you need to have a little knowledge on how these services actually work. if you go to any of these short urls, they tell your browser “HTTP 30X: Object has moved” HTTP HEADER (optionally, some does it, some doesn’t) and then asks your browser to move to the original url using “Location” in HTTP HEADER. so all you have to do is just get the HTTP HEADER out first (PHP and Curl is pretty good at doing this, heh heh) and then parse the “Location” parameter from it.

lets see how that works in code


Copy this code and paste it in your HTML
  1. < ?php
  2. $url = "http://tinyurl.com/2dfmty";
  3. $ch = curl_init($url);
  4. curl_setopt($ch,CURLOPT_HEADER,true);
  5. curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  6. curl_setopt($ch, CURLOPT_FOLLOWLOCATION,false);
  7. $data = curl_exec($ch);
  8. $pdata = http_parse_headers($data);
  9. echo "Short URL: {$url}<br/>";
  10. echo "Original URL: {$pdata['Location']}";
  11.  
  12.  
  13. function http_parse_headers( $header )
  14. {
  15. $retVal = array();
  16. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
  17. foreach( $fields as $field ) {
  18. if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
  19. $match[1] = preg_replace('/(?< =^|[\x09\x20\x2D])./e', 'strtoupper("")', strtolower(trim($match[1])));
  20. if( isset($retVal[$match[1]]) ) {
  21. $retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
  22. } else {
  23. $retVal[$match[1]] = trim($match[2]);
  24. }
  25. }
  26. }
  27. return $retVal;
  28. }
  29. ?>
  30.  
  31. now you see that the output of this code is
  32.  
  33. Short URL: http://tinyurl.com/2dfmty
  34. Original URL: http://ghill.customer.netspace.net.au/embiggen/

URL: http://hasin.me/2009/05/05/expanding-short-urls-to-original-urls-using-php-and-curl/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.