Skip to content

Instantly share code, notes, and snippets.

@aegypius
Forked from rduarte/base62.php
Created April 30, 2010 12:36
Show Gist options
  • Save aegypius/385126 to your computer and use it in GitHub Desktop.
Save aegypius/385126 to your computer and use it in GitHub Desktop.
Base62 Encoding/Decoding
<?php
function base62_encode($num){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
$result = '';
while($num >= $base) {
$r = $num%$base;
$result = $chars[$r].$result;
$num = $num/$base;
}
return $chars[$num].$result;
}
function base62_decode($id){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
for ($i=0; $i<strlen($id); $i++) {
$value = strpos($chars, $id[$i]);
$num = $value * pow($base, strlen($id)-($i+1));
$final += $num;
}
return $final;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment