Return to Snippet

Revision: 58867
at August 7, 2012 18:23 by kh411d


Initial Code
/**
 * CodeIgniter ShortURL Library
 *
 * Create and Translate ShortURL from integer ID 
 *
 * @location    Application/libraries
 * @package     CodeIgniter
 * @author      Khalid Adisendjaja < [email protected] > 
 * @website		http://khalidadisendjaja.web.id
 */
 
Class Shorturl {
  
  protected $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  protected $prefix;

	function __construct(){}
	
	public function setPrefix($p)
	{
	 $this->prefix = $p;
	}
	
	public function createURL($base_url,$id)
	{
	  return $base_url.$this->intToKeyword($id);
	}
	
	public function getURL($base_redirect_url,$keyword)
	{
	  if($id = $this->keywordToInt($keyword)){
		return $base_redirect_url.$id;
	  }else{
	    return null;
	  }
	}
	
	public function intToKeyword($url_id)
	{
		$base = strlen($this->codeset);
		$n = $url_id;
		$converted = "";
		while ($n > 0) {
		  $converted = substr($this->codeset, ($n % $base), 1) . $converted;
		  $n = floor($n/$base);
		}
		return $this->prefix ? $this->prefix.$converted : $converted;
	}

	public function keywordToInt($keyword)
	{  
	  if($this->prefix){
		  if(preg_match('/^'.$this->prefix.'([0-9a-zA-Z]+)$/',$keyword,$matches)){
			 $keyword = $matches[1];
		   }else{
			return null;
		   }
	  }
		$base = strlen($this->codeset);
		$converted = $keyword;
		$c = 0;
		for ($i = strlen($converted); $i; $i--) {
		  $c += strpos($this->codeset, substr($converted, (-1 * ( $i - strlen($converted) )),1)) * pow($base,$i-1);
		}
		return $c;
	}
		
}

Initial URL

                                

Initial Description
Create short url easy by modifying integer to characters

Initial Title
shortURL for PHP

Initial Tags

                                

Initial Language
PHP