Top

Shortening URLs on the fly in PHP

May 1, 2009

For a project I’m currently working on, I wanted to parse input strings looking for URLs and convert them to shortened URLs.  The best service to do this in is CR.AM, which is like competing URL shortening services but with some extra features like phishing/spam protection, Twitter integration, and more.  If you are doing anything involving Twitter, I highly recommend using cr.am for your URL shortening, as they’ve got some really neat things on the horizon involving Twitter.

More importantly, though, getting it set up was easy.  There are two functions: one tokenizes the string to search the string for URLs (in my case, I’m looking for a string that begins with http:// or www. but your needs may vary). Many people would use regular expressions here, I didn’t.   My strings are short and easy to parse this way. This post isn’t about how to find URLs in a string, it’s about how to shrink them.

The second function calls up cr.am and requests a hash for the URL.  To convert URLs in a string to cr.am URLs, you just pass the string to cramify() and use the output.

  1. function cram ($url) {
  2.     $cramHash = @file_get_contents(‘http://api.cr.am/create/’ . $url);
  3.  
  4.     list($httpVersion, $statusCode, $message) = explode(‘ ‘,$http_response_header[0], 3);
  5.  
  6.     if ($statusCode == 200) {
  7.         return "http://cr.am/".$cramHash;
  8.     } else {
  9.         return "";
  10.     }
  11. }
  12.  
  13. function cramify ($string) {
  14.     $tokens = explode(" ",$string);
  15.  
  16.     foreach ($tokens AS $t) {
  17.         if (substr($t,0,7) == "http://") {
  18.             $string = str_replace($t, cram($t), $string);
  19.         } else if (substr($t,0,4) == "www." && substr($t,4,1) != " ") {
  20.             $string = str_replace($t, cram("http://".$t), $string);
  21.         }
  22.     }
  23.  
  24.     return $string;
  25. }

Bottom