Home > Backend Development > PHP Tutorial > Six ways to rename uploaded images in PHP

Six ways to rename uploaded images in PHP

WBOY
Release: 2016-07-25 08:55:36
Original
1866 people have browsed it
  1. /*
  2. com_create_guid() is a function supported by the php5 version. For unsupported versions, you can define it yourself;
  3. */
  4. function guid(){
  5. if (function_exists('com_create_guid ')){
  6. return com_create_guid();
  7. }else{
  8. mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
  9. echo(mt_rand());
  10. $charid = strtoupper(md5(uniqid(rand(), true)));
  11. $hyphen = chr(45);// "-"
  12. $uuid = chr(123)// "{"
  13. .substr($charid, 0 , 8).$hyphen
  14. .substr($charid, 8, 4).$hyphen
  15. .substr($charid,12, 4).$hyphen
  16. .substr($charid,16, 4).$hyphen
  17. . substr($charid,20,12)
  18. .chr(125);// "}"
  19. return $uuid;
  20. }
  21. }
Copy code

2, MD5: Like guid, a 32-character hexadecimal number will be output. The difference is that guid is randomly generated, and md5 needs to be generated based on the input data. example:

  1. $str = "Hello";
  2. echo md5($str);
  3. ?>
Copy code

Output result: 8b1a9953c4611296a827abf8c47804d7 Advantages: The output value can be controlled based on the input seed data. If the seed data is regular and non-repeating, the data can be protected through md5, which will cause great confusion. Disadvantages: 32-bit characters are too long; unique seed data needs to be provided; Usage: High concurrency, using seconds as the seed data, duplication will still occur. example:

  1. /*
  2. * Used in combination with the time() function, using the number of seconds from 1970 to the current time as the seed number.
  3. */
  4. $str=time();
  5. echo md5($str);
  6. ?>
Copy code

3, uniqid(): return 13 or 23-digit string For our purposes, uniqid() is like an improved version of md5(), especially since we can use differential identifiers as string prefixes, which can reduce the chance of repeated naming. For extreme situations such as non-high concurrency, it is recommended to use this function, which can already meet general needs.

Definition: The uniqid() function generates a unique ID based on the current time in microseconds. Usage: uniqid(prefix,more_entropy) Note: prefix can add a prefix to the output string. The example is as follows. When the more_entropy parameter is true, a 23-bit string will be output.

Example:

  1. var_dump(uniqid());
  2. var_dump(uniqid("a"));
  3. ?>
Copy code

Output result: string(13) "51734aa562254" string(14) "a51734aa562257" Advantages: 13-digit string length is an acceptable file naming length; prefixes can be added, and the result contains data obfuscation, which can avoid back-referencing the original data. Disadvantages: Similar to md5, high concurrency, using seconds as the seed data, duplication will still occur.

3. Upgraded version plan: 1. fast_uuid: returns 17 digits A bit like an incompletely customized version of uniqid(), the concept of "seed number starting time" that appears in this function is very enlightening. The default time used in time() and uniqid() is calculated from 1970, and the length is ten digits (1366512439). Using the "seed number starting time" can reduce this value. Because, from the actual demand point of view, it is just a value that can grow automatically. After the start time is customized, in addition to reducing the length, it can also play a role in confusion.

Example:

  1. /*

  2. * The parameter suffix_len specifies how many random digits are appended to the generated ID value. The default value is 3.
  3. * Thanks to "Ivan Tan| Tan Junqing DrinChing (at) Gmail.com" for providing the algorithm.
  4. * @param int suffix_len
  5. * @return string
  6. */
  7. function fast_uuid($suffix_len=3){
  8. //! The starting time for calculating the seed number
  9. $being_timestamp = strtotime('2013-3-21');< ;/p>
  10. $time = explode(' ', microtime());

  11. $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0 ], 2, 6));
  12. if ($suffix_len > 0)
  13. {
  14. $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
  15. }
  16. return $id ;
  17. }

Copy code

Output result: 29832412631099013

2, time()+random number: The use of random numbers has appeared in the above example to solve multiple requests that occur in one second. Two functions are provided:

  1. function random($length) {
  2. $hash = '';
  3. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
  4. $max = strlen($chars) - 1 ;
  5. PHP_VERSION < ' 4.2.0' && mt_srand((double)microtime() * 1000000);
  6. for($i = 0; $i < $length; $i++) {
  7. $hash .= $chars[mt_rand(0, $max )];
  8. } // bbs.it-home.org
  9. return $hash;
  10. }
  11. function random2($length, $numeric = 0) {
  12. PHP_VERSION < '4.2.0' ? mt_srand((double)microtime () * 1000000) : mt_srand();
  13. $seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
  14. $seed = $numeric ? (str_replace ('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
  15. $hash = '';
  16. $max = strlen($seed) - 1 ;
  17. for($i = 0; $i < $length; $i++) {
  18. $hash .= $seed[mt_rand(0, $max)];
  19. }
  20. return $hash;
  21. }
  22. ?>
Copy code

4. Final plan: Idea: userid+second+random number. Among them, "userid+second" is converted from decimal to 64, reducing the number of digits; illustrate: userid: The maximum value of "ZZZZ" in hexadecimal is converted to decimal equal to "16777215", and the maximum value of "ZZZ" converted to decimal is equal to "262143"; Seconds: Set your own time starting point.

  1. const KeyCode = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  2. /**
  3. * Convert a 64-digit string to a decimal string
  4. * @param $m string 64-digit string
  5. * @param $len integer Returns the length of the string, if the length is not enough, use 0 Padding, 0 means no padding
  6. * @return string
  7. * @author 野马
  8. */
  9. function hex64to10 ($m, $len = 0) {
  10. $m = (string)$m;
  11. $hex2 = '';
  12. $Code = KeyCode;
  13. for($i = 0, $l = strlen($Code); $i < $l; $i++) {
  14. $KeyCode [] = $Code[$i];
  15. }
  16. $KeyCode = array_flip($KeyCode);

  17. for($i = 0, $l = strlen($m); $i < $l; $i++) {

  18. $one = $m[$i];
  19. $hex2 .= str_pad(decbin($KeyCode[$one]), 6, '0', STR_PAD_LEFT);
  20. }
  21. $ return = bindec($hex2);

  22. if($len) {

  23. $clen = strlen($return);
  24. if($clen >= $len) {
  25. return $return ;
  26. }
  27. else {
  28. return str_pad($return, $len, '0', STR_PAD_LEFT);
  29. }
  30. }
  31. return $return;
  32. }

  33. /**

  34. * Convert the decimal number string to the 64-base number string
  35. * @param $m string The decimal number string
  36. * @param $len integer Returns the string length, if the length is not enough, use 0 Padding, 0 means no padding
  37. * @return string
  38. * @author 野马
  39. */
  40. function hex10to64($m, $len = 0) {
  41. $KeyCode = KeyCode;
  42. $hex2 = decbin($m);
  43. $hex2 = str_rsplit($hex2, 6);
  44. $hex64 = array() ;
  45. foreach($hex2 as $one) {
  46. $t = bindec($one);
  47. $hex64[] = $KeyCode[$t];
  48. }
  49. $return = preg_replace('/^0*/', '', implode('', $hex64));
  50. if($len) {
  51. $clen = strlen($return);
  52. if($clen >= $len) {
  53. return $return;
  54. }
  55. else {
  56. return str_pad($return, $len, '0', STR_PAD_LEFT);
  57. }
  58. }
  59. return $return;
  60. }

  61. /**

  62. * Convert hexadecimal number string to hexadecimal number string
  63. * @param $m string Hexadecimal number string
  64. * @param $len integer Returns the string length, if the length is not enough, use 0 Padding, 0 means no padding
  65. * @return string
  66. * @author 野马
  67. */
  68. function hex16to64($m, $len = 0) {
  69. $KeyCode = KeyCode;
  70. $hex2 = array();
  71. for($i = 0, $j = strlen($m); $i < $j; + +$i) {
  72. $hex2[] = str_pad(base_convert($m[$i], 16, 2), 4, '0', STR_PAD_LEFT);
  73. }
  74. $hex2 = implode('', $hex2) ;
  75. $hex2 = str_rsplit($hex2, 6);
  76. foreach($hex2 as $one) {
  77. $hex64[] = $KeyCode[bindec($one)];
  78. }
  79. $return = preg_replace('/^ 0*/', '', implode('', $hex64));
  80. if($len) {
  81. $clen = strlen($return);
  82. if($clen >= $len) {
  83. return $ return;
  84. }
  85. else {
  86. return str_pad($return, $len, '0', STR_PAD_LEFT);
  87. }
  88. }
  89. return $return;
  90. }

  91. /**

  92. * The function is close to the PHP native function str_split, except that the cutting starts from the end
  93. * @param $str string The string that needs to be cut
  94. * @param $len integer The length of each string
  95. * @return array
  96. * @author Mustang
  97. */
  98. function str_rsplit($str, $len = 1) {
  99. if($str == null || $str == false || $str == '') return false;
  100. $strlen = strlen($ str);
  101. if($strlen <= $len) return array($str);
  102. $headlen = $strlen % $len;
  103. if($headlen == 0) {
  104. return str_split($str, $len );
  105. }
  106. $return = array(substr($str, 0, $headlen));
  107. return array_merge($return, str_split(substr($str, $headlen), $len));
  108. }
  109. $a=idate("U");

  110. echo "rn
    e:" . hex10to64($a);
  111. echo "rn
    e:" . hex64to10 (hex10to64($a));

Copy code

算法2:

  1. function dec2s4($dec) {
  2. $base = '0123456789_$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3. $result = '';

  4. do {

  5. $result = $base[$dec % 64] . $result;
  6. $dec = intval($dec / 64);
  7. } while ($dec != 0);

  8. return $result;

  9. }

  10. function s42dec($sixty_four) {

  11. $base_map = array ( '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, '_' => 10, '$' => 11, 'a' => 12, 'b' => 13, 'c' => 14, 'd' => 15, 'e' => 16, 'f' => 17, 'g' => 18, 'h' => 19, 'i' => 20, 'j' => 21, 'k' => 22, 'l' => 23, 'm' => 24, 'n' => 25, 'o' => 26, 'p' => 27, 'q' => 28, 'r' => 29, 's' => 30, 't' => 31, 'u' => 32, 'v' => 33, 'w' => 34, 'x' => 35, 'y' => 36, 'z' => 37, 'A' => 38, 'B' => 39, 'C' => 40, 'D' => 41, 'E' => 42, 'F' => 43, 'G' => 44, 'H' => 45, 'I' => 46, 'J' => 47, 'K' => 48, 'L' => 49, 'M' => 50, 'N' => 51, 'O' => 52, 'P' => 53, 'Q' => 54, 'R' => 55, 'S' => 56, 'T' => 57, 'U' => 58, 'V' => 59, 'W' => 60, 'X' => 61, 'Y' => 62, 'Z' => 63, );
  12. $result = 0;
  13. $len = strlen($sixty_four);

  14. for ($n = 0; $n < $len; $n++) {

  15. $result *= 64;
  16. $result += $base_map[$sixty_four{$n}];
  17. }

  18. return $result;

  19. }

  20. $a=idate("U");

  21. var_dump(dec2s4($a));
  22. var_dump(s42dec(dec2s4($a)));

复制代码

算法效率测试:

  1. $strarr = array();

  2. $time1 = microtime(true);
  3. for($i = 0; $i < 10000; ++$i) {
  4. $str = idate("U")+$i;
  5. $strarr[] = "{$i}->$strrn
    ";
  6. }
  7. $time2 = microtime(true);
  8. $time3 = $time2 - $time1;

  9. $time1 = microtime(true);

  10. for($i = 0; $i < 10000; ++$i) {
  11. $str = dec2s4(idate("U")+$i);
  12. $strarr[] = "{$i}->$strrn
    ";
  13. }
  14. $time2 = microtime(true);
  15. echo "rn
    运行10000次用时(秒):" . ($time2 - $time1 - $time3);

复制代码

测试结果: 算法1:0.1687250137329 算法2:0.044965028762817 结论:算法1虽然效率上差一些,但是可以把md5生成的16进制转化为64进制,能够使用在必须使用md5的环境下缩短字符串。

六、总结 本文内容的关键点是使用10进制转换为64进制来进行字符串的缩减。 例如,使用fast_uuid生成的17位数字,转换为64进制仅有7位字符;

以上就是有关php上传图片重命名的全部内容了,希望对大家有所帮助。



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template