shortURL for PHP


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

Create short url easy by modifying integer to characters


Copy this code and paste it in your HTML
  1. /**
  2.  * CodeIgniter ShortURL Library
  3.  *
  4.  * Create and Translate ShortURL from integer ID
  5.  *
  6.  * @location Application/libraries
  7.  * @package CodeIgniter
  8.  * @author Khalid Adisendjaja < [email protected] >
  9.  * @website http://khalidadisendjaja.web.id
  10.  */
  11.  
  12. Class Shorturl {
  13.  
  14. protected $codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  15. protected $prefix;
  16.  
  17. function __construct(){}
  18.  
  19. public function setPrefix($p)
  20. {
  21. $this->prefix = $p;
  22. }
  23.  
  24. public function createURL($base_url,$id)
  25. {
  26. return $base_url.$this->intToKeyword($id);
  27. }
  28.  
  29. public function getURL($base_redirect_url,$keyword)
  30. {
  31. if($id = $this->keywordToInt($keyword)){
  32. return $base_redirect_url.$id;
  33. }else{
  34. return null;
  35. }
  36. }
  37.  
  38. public function intToKeyword($url_id)
  39. {
  40. $base = strlen($this->codeset);
  41. $n = $url_id;
  42. $converted = "";
  43. while ($n > 0) {
  44. $converted = substr($this->codeset, ($n % $base), 1) . $converted;
  45. $n = floor($n/$base);
  46. }
  47. return $this->prefix ? $this->prefix.$converted : $converted;
  48. }
  49.  
  50. public function keywordToInt($keyword)
  51. {
  52. if($this->prefix){
  53. if(preg_match('/^'.$this->prefix.'([0-9a-zA-Z]+)$/',$keyword,$matches)){
  54. $keyword = $matches[1];
  55. }else{
  56. return null;
  57. }
  58. }
  59. $base = strlen($this->codeset);
  60. $converted = $keyword;
  61. $c = 0;
  62. for ($i = strlen($converted); $i; $i--) {
  63. $c += strpos($this->codeset, substr($converted, (-1 * ( $i - strlen($converted) )),1)) * pow($base,$i-1);
  64. }
  65. return $c;
  66. }
  67.  
  68. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.