PHP tiny url encode and decode functions


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

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:


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.