Created
December 14, 2017 19:44
-
-
Save lcherone/bc1a53cd8a8e67aaa298ca3f55bf9f67 to your computer and use it in GitHub Desktop.
Basic encode an int into a short hash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Encode an int into a short hash. | |
* | |
* @param int $id | |
* @param string|int $seed - Lock alphabet shuffle, or leave blank for random | |
* @return string | |
*/ | |
function id_encode(int $id, $seed = null) { | |
$alphabet = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'); | |
if ($seed !== null) { | |
@mt_srand($seed); | |
for ($i = count($alphabet)-1; $i > 0; $i--) { | |
$a = @mt_rand(0, $i); | |
$t = $alphabet[$i]; | |
$alphabet[$i] = $alphabet[$a]; | |
$alphabet[$a] = $t; | |
} | |
} else { | |
shuffle($alphabet); | |
} | |
$value = base_convert($id+"1e3", 10, 36); | |
$out = ''; | |
foreach (str_split($value) as $key => $value) { | |
$out .= $alphabet[$key].$value; | |
} | |
return str_rot13($out); | |
} | |
/** | |
* Decodes hash into int | |
* | |
* @param string $hash | |
* @return int | |
*/ | |
function id_decode($str) { | |
$str = str_rot13($str); | |
$out = ''; | |
foreach (str_split($str) as $key => $value) { | |
if ($key % 2 != 0) { | |
$out .= $value; | |
} | |
} | |
return base_convert($out, 36, 10)-"1e3"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment