Posted By

ginoplusio on 12/29/09


Tagged

curl url encode short filegetcontents tinyurl tiny


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

adix
ginoplusio
pster
BrianCoyDesign


PHP tiny url encode and decode functions


 / Published in: PHP
 

URL: http://www.barattalo.it/2009/12/29/tiny-url-encode-and-decode-with-php/

The first function make short urls. The second function decode a short url with CURL. It gets the http header of the short url page. If the header contains a "Location:" header, then it's a redirect, and the decoded url is the url in the "Location" header string, here is the code:

  1. function doShortURL($url) {
  2. $short_url= file_get_contents('http://tinyurl.com/api-create.php?url=' . urlencode( $url ) );
  3. return $short_url;
  4. }
  5.  
  6.  
  7. function doShortURLDecode($url) {
  8. $ch = @curl_init($url);
  9. @curl_setopt($ch, CURLOPT_HEADER, TRUE);
  10. @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  11. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  12. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  13. $response = @curl_exec($ch);
  14. preg_match('/Location: (.*)\n/', $response, $a);
  15. if (!isset($a[1])) return $url;
  16. return $a[1];
  17. }

Report this snippet  

You need to login to post a comment.