Skip to content

Instantly share code, notes, and snippets.

@zhangv
Created May 10, 2018 03:22
Show Gist options
  • Save zhangv/4ffb232ccec7614539db56d4795b8630 to your computer and use it in GitHub Desktop.
Save zhangv/4ffb232ccec7614539db56d4795b8630 to your computer and use it in GitHub Desktop.
UrlShortener
<?php
class UrlShortener{
private static $base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';//the real base should not be easy to guess
private static $len = 5;
private $salt = 0; //simple salt strategy - just shift the base
public function __construct($salt = 0){
$this->salt = $salt;
}
public function base(){
$a = str_split(self::$base);
$b = array_slice($a,0,$this->salt);
array_splice($a,0,$this->salt);
return array_merge($a,$b);
}
public function encode($num) {
$ar = $this->base();
$r = [];
$size = count($ar);
while($num > 0){
$r[] = $ar[(int)($num % $size) ];
$num = (int) ($num / $size);
}
return str_pad(implode('',array_reverse($r)),self::$len,$ar[0],STR_PAD_LEFT);
}
public function decode($str) {
$basearr = $this->base();
$baselen = count($basearr);
$ar = str_split($str);
$size = count($ar);
$r = 0;
for($i = 0;$i<$size;$i++){
$r = $r*$baselen + array_search($ar[$i],$basearr);
}
return $r;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment