rduarte (owner)

Revisions

gist: 89540 Download_button fork
public
Description:
base62 algorithm - encode and decode
Public Clone URL: git://gist.github.com/89540.git
Embed All Files: show embed
base62.php #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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;
}
?>