Skip to content

Instantly share code, notes, and snippets.

@simmo
Created June 12, 2012 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simmo/2920592 to your computer and use it in GitHub Desktop.
Save simmo/2920592 to your computer and use it in GitHub Desktop.
Base58 Trait (like Base62) Encode/Decode
//
// Base58 Encode/Decode Trait for PHP
// ==================================
// Base58 is like Base62 except that it removes certain problematic characters such as 0, O, I, and l.
// This is great if you need the encoded output to be easily human-readable. Like short URLs...
//
trait Base58 {
private $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
function base63_encode($num) {
$base_count = strlen($this->alphabet);
$encoded = '';
while ($num >= $base_count) {
$div = $num / $base_count;
$mod = ($num - ($base_count * intval($div)));
$encoded = $this->alphabet[$mod] . $encoded;
$num = intval($div);
}
if ($num) $encoded = $this->alphabet[$num] . $encoded;
return $encoded;
}
function base63_decode($num) {
$decoded = 0;
$multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num) - 1];
$decoded += $multi * strpos($this->alphabet, $digit);
$multi = $multi * strlen($this->alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment