Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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";
- }
Add Comment
Please, Sign In to add comment