PHP随机URL名称(短URL)

前端之家收集整理的这篇文章主要介绍了PHP随机URL名称(短URL)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在使用像JSFiddle这样的网站之后,我注意到他们自动生成由各种大小写字符组成的随机和唯一的URL.

我们可以从我们的预订页面中受益.怎么做

这不是随机的,根据您的数据库记录的ID.

怎么运行的:

基本上你有一个字符串是唯一的,但它可以解密代表一个数字,你应该把它看作一个简短的加密/解密.

您有一个函数可以使用唯一的ID,然后从该ID创建一个唯一的“短字符串”,然后可以反转该过程以从短字符串中获取唯一的ID.

这是一个我已经找到一个网站的剪辑:

  1. function alphaID($in,$to_num = false,$pad_up = false,$passKey = null)
  2. {
  3. $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  4. if ($passKey !== null)
  5. {
  6. /* Although this function's purpose is to just make the
  7. * ID short - and not so much secure,* with this patch by Simon Franz (http://blog.snaky.org/)
  8. * you can optionally supply a password to make it harder
  9. * to calculate the corresponding numeric ID */
  10.  
  11. for ($n = 0; $n<strlen($index); $n++)
  12. {
  13. $i[] = substr( $index,$n,1);
  14. }
  15.  
  16. $passhash = hash('sha256',$passKey);
  17.  
  18. $passhash = (strlen($passhash) < strlen($index)) ? hash('sha512',$passKey) : $passhash;
  19.  
  20. for ($n=0; $n < strlen($index); $n++)
  21. {
  22. $p[] = substr($passhash,1);
  23. }
  24.  
  25. array_multisort($p,SORT_DESC,$i);
  26. $index = implode($i);
  27. }
  28.  
  29. $base = strlen($index);
  30.  
  31. if ($to_num)
  32. {
  33. // Digital number <<-- alphabet letter code
  34. $in = strrev($in);
  35. $out = 0;
  36. $len = strlen($in) - 1;
  37.  
  38. for ($t = 0; $t <= $len; $t++)
  39. {
  40. $bcpow = bcpow($base,$len - $t);
  41. $out = $out + strpos($index,substr($in,$t,1)) * $bcpow;
  42. }
  43.  
  44. if (is_numeric($pad_up))
  45. {
  46. $pad_up--;
  47. if ($pad_up > 0)
  48. {
  49. $out -= pow($base,$pad_up);
  50. }
  51. }
  52. $out = sprintf('%F',$out);
  53. $out = substr($out,strpos($out,'.'));
  54. }
  55. else
  56. {
  57. // Digital number -->> alphabet letter code
  58. if (is_numeric($pad_up))
  59. {
  60. $pad_up--;
  61. if ($pad_up > 0)
  62. {
  63. $in += pow($base,$pad_up);
  64. }
  65. }
  66.  
  67. $out = "";
  68. for ($t = floor(log($in,$base)); $t >= 0; $t--)
  69. {
  70. $bcp = bcpow($base,$t);
  71. $a = floor($in / $bcp) % $base;
  72. $out = $out . substr($index,$a,1);
  73. $in = $in - ($a * $bcp);
  74. }
  75. $out = strrev($out); // reverse
  76. }
  77. return $out;
  78. }

  1. alphaID(9007199254740989); //-> PpQXn7COf
  2. alphaID('PpQXn7COf',true); //-> 9007199254740989

这里有一个脚本链接https://github.com/kvz/deprecated/blob/kvzlib/php/functions/alphaID.inc.php

猜你在找的PHP相关文章