Showing posts with label urlshortener. Show all posts
Showing posts with label urlshortener. Show all posts

Sep 14, 2011

URL shortening - make your own URL shortener

If you ever thought about URL shortening, you've probably already figured out, how it works.

Those random letters and numbers which serve as a key (in hashtable data structures) are basically encoded integers, which are AUTO_INCREMENT values in the database.

Here are the encoding and decoding functions:
const ALLOWED_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

function id2short($integer, $base = self::ALLOWED_CHARS) {
	$out = '';
	$length = strlen($base);
	while($integer > $length-1) {
		$out = $base[fmod($integer, $length)].$out;
		$integer = floor( $integer / $length);
	}
	return $base[$integer].$out;
}

function short2id($string, $base = self::ALLOWED_CHARS) {
	$length = strlen($base);
	$size = strlen($string)-1;
	$string = str_split($string);
	$out = strpos($base, array_pop($string));
	foreach($string as $i=>$char) {
		$out += strpos($base, $char) * pow($length, $size - $i);
	}
	return $out;
}

Full code here.

Jul 19, 2011

PHP goo.gl url shortener

Here's an implementation of Google's url shortener: goo.gl.
<?
class googl {
 const api = 'https://www.googleapis.com/urlshortener/v1/url';
 private $key = null;
 
 public function __construct($key = null) {
  if(defined('GOOGLE_API_KEY')) {
   $this->setKey(GOOGLE_API_KEY);
  }
  
  if(!is_null($key)) {
   $this->setKey($key);
  }
 }
 
 public function setKey($key) {
  $this->key = $key;
 }
 
 public function s($url) {
  $data = $this->shorten($url);
  return isset($data->id) ? $data->id : $url;
 }
 
 public function shorten($url) {
  $key = '';
  $data = array();
  $data['longUrl'] = $url;
  
  if(!is_null($this->key)) {
   $key = '?key='.$this->key;
  }
  
  return $this->fetch(self::api.$key,$data);
 }
 
 public function expand($url) {
  $key = is_null($this->key) ? '' : "&key={$this->key}";
  return $this->fetch(self::api.'?shortUrl='.urlencode($url)."$key&projection=FULL");
 }
 
 private function fetch($url, $data = array()) {
  $ch = curl_init();
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  
  if(!empty($data)) {
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  }
  
  $r = curl_exec($ch);
  curl_close($ch);
  
  return json_decode($r);
 }
}
?>