Guest User

Untitled

a guest
Dec 17th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. <?php
  2. /**
  3. * Encode an int into a short hash.
  4. *
  5. * @param int $id
  6. * @param string|int $seed - Lock alphabet shuffle, or leave blank for random
  7. * @return string
  8. */
  9. function id_encode(int $id, $seed = null) {
  10. $alphabet = str_split('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
  11.  
  12. if ($seed !== null) {
  13. @mt_srand($seed);
  14. for ($i = count($alphabet)-1; $i > 0; $i--) {
  15. $a = @mt_rand(0, $i);
  16. $t = $alphabet[$i];
  17. $alphabet[$i] = $alphabet[$a];
  18. $alphabet[$a] = $t;
  19. }
  20. } else {
  21. shuffle($alphabet);
  22. }
  23.  
  24. $value = base_convert($id+"1e3", 10, 36);
  25.  
  26. $out = '';
  27. foreach (str_split($value) as $key => $value) {
  28. $out .= $alphabet[$key].$value;
  29. }
  30.  
  31. return str_rot13($out);
  32. }
  33.  
  34. /**
  35. * Decodes hash into int
  36. *
  37. * @param string $hash
  38. * @return int
  39. */
  40. function id_decode($str) {
  41. $str = str_rot13($str);
  42.  
  43. $out = '';
  44. foreach (str_split($str) as $key => $value) {
  45. if ($key % 2 != 0) {
  46. $out .= $value;
  47. }
  48. }
  49. return base_convert($out, 36, 10)-"1e3";
  50. }
Add Comment
Please, Sign In to add comment