A detailed introduction of six solutions to rename uploaded images based on php

  • 2020-06-01 08:27:21
  • OfStack

1. Applicable scenario: unable to use the self-growing number returned from the database, rename the uploaded image.

This is determined by the process of uploading pictures or files.
1. The image upload process is to upload the image to the server, rename it and insert it into the database.
In other words, the self-growing id, which is easily available in the database, cannot be used to rename uploaded images to avoid duplicate file names,
However, the method of obtaining the maximum id plus 1 from the database increases the number of database connections, which is not suitable for high concurrency and large amount of data.

2. General scheme:

1, guid: 32 characters in base 106.
Format: the format of GUID is "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", where each x is a 32-bit hexadecimal number in the range of 0-9 or a-f. For example: 6 F9619FF - 8 B86 - D011 - B42D - 00 C04FC964FF GUID value is effective.

Advantages: almost no repetition;
Cons: too long to rename uploaded images.
Usage:


/*
    com_create_guid() is php5 Version support functions, for the version is not supported, you can define their own; 
*/
function guid(){
   if (function_exists('com_create_guid')){
       return com_create_guid();
   }else{
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       echo(mt_rand());
       $charid = strtoupper(md5(uniqid(rand(), true)));
       $hyphen = chr(45);// "-"
       $uuid = chr(123)// "{"
               .substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12)
               .chr(125);// "}"
       return $uuid;
   }
}

2, MD5:
Like guid 1, it will output 32 characters in base 106. The difference is that guid is randomly generated, while md5 needs to be generated according to the input data.
Example,

<?php
$str = "Hello";
echo md5($str);
?>

The output,

8b1a9953c4611296a827abf8c47804d7

Advantages: the output value can be controlled according to the input seed data. If the seed data are not repeated regularly, the data can be protected through md5, resulting in great confusion.
Disadvantages: 32-bit characters are too long; Non-repeatable seed data shall be provided;
Usage: high concurrency, in the second as the seed data, still can appear the duplication phenomenon.

<?php
/*
* In combination with time() The function is used to 1970 The number of seconds from year to current time is used as the seed number. 
*/
$str=time();
echo md5($str);
?>

3, uniqid() : returns a 13 - or 23-bit string.
For our purposes, uniqid() is like an improved version of md5(), especially since we can use the difference identifier as a string prefix to reduce the chance of duplicate naming.
For extreme cases such as non-high concurrency, it is recommended to use this function, which can already meet 1 generic requirements.
Specify,
Definition: the uniqid() function generates a 1-only ID based on the current time in microseconds.
Usage: uniqid (prefix more_entropy)
Note: prefix can prefix an output string, as shown in the following example, when the more_entropy parameter is true, a 23-bit string will be output.

<?php
var_dump(uniqid());
var_dump(uniqid("a"));
?>

The output result is:

string(13) "51734aa562254" string(14) "a51734aa562257"

Advantages: 13-bit string length, is an acceptable file name length; Prefixes can be added, and the results contain data obfuscation to avoid backpushing the original data.
Disadvantages: similar to md5, high concurrency, seed-data in seconds, still repeated.

3. Upgrade scheme:

1, fast_uuid: returns 17 digits.
Somewhat like an incomplete custom version of uniqid(), the "seed count start time" concept that appears in this function is instructive.
The default time used in time() and uniqid() has been calculated since 1970, with a length of 10 bits (1366512439). The "seed number start time" can reduce this value, because what we really need is only one value that can be automatically increased.
After the start time is customized, in addition to reducing the length, it can also play a confusing role.


/*
*  parameter  suffix_len The specified   The generated  ID  The default value is  3 . 
*  Thank you" Ivan Tan| Tan Junqing  DrinChing (at) Gmail.com "Provides the algorithm. 
* @param int suffix_len
* @return string
*/
function fast_uuid($suffix_len=3){
        //!  Calculate the start time of the seed count 
        $being_timestamp = strtotime('2013-3-21');

        $time = explode(' ', microtime());
        $id = ($time[1] - $being_timestamp) . sprintf('%06u', substr($time[0], 2, 6));
        if ($suffix_len > 0)
        {
            $id .= substr(sprintf('%010u', mt_rand()), 0, $suffix_len);
        }
        return $id;
    }

The output,

29832412631099013

2, time()+ random number:

The use of random Numbers is already present in the above example to resolve multiple requests that occur in 1 second. Two functions are provided as follows,


<?php
function random($length) {
    $hash = '';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
function random2($length, $numeric = 0) {
    PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
    $seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $seed[mt_rand(0, $max)];
    }
    return $hash;
}
?>

4. Final plan:

Idea: userid+ seconds + random Numbers. Where "userid+ seconds" is converted from 10 to 64, reducing the number of digits;

Description:
1, userid: hexadecimal Max "ZZZZ" converted to hexadecimal Max is" 16777215 ", "ZZZ" converted to hexadecimal Max is "262143";
2. Seconds: set your own time starting point.
$less = time () - strtotime (' 2012-4-21 '); Convert to hexadecimal "1SpRe", 5 bits
$less = time () - strtotime (' 2013-3-21 '); Convert to base 64 "_jHY"; four
3. Random Numbers: random(3) is used to generate 3-bit random Numbers;

Final results:
4 bit userid+4 bit seconds +3 bit random number =11 bit string. Although the results look similar to uniqid(), the strength is improved.

5,10 to 64 algorithm:

1. Algorithm 1:


View Code 
const KeyCode = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';

    /**
     *  will 64 The base number string is converted 10 A string of digits in base 
     * @param $m string 64 A string of digits in base 
     * @param $len integer  Returns the length of the string, if insufficient 0 Fill, 0 Is not fill 
     * @return string
     * @author  Wild horses 
     */
    function hex64to10($m, $len = 0) {
        $m = (string)$m;
        $hex2 = '';
        $Code = KeyCode;
        for($i = 0, $l = strlen($Code); $i < $l; $i++) {
            $KeyCode[] = $Code[$i];
        }
        $KeyCode = array_flip($KeyCode);

        for($i = 0, $l = strlen($m); $i < $l; $i++) {
            $one = $m[$i];
            $hex2 .= str_pad(decbin($KeyCode[$one]), 6, '0', STR_PAD_LEFT);
        }
        $return = bindec($hex2);

        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, '0', STR_PAD_LEFT);
            }
        }
        return $return;
    }

    /**
     *  will 10 The base number string is converted 64 A string of digits in base 
     * @param $m string 10 A string of digits in base 
     * @param $len integer  Returns the length of the string, if insufficient 0 Fill, 0 Is not fill 
     * @return string
     * @author  Wild horses 
     */
    function hex10to64($m, $len = 0) {
        $KeyCode = KeyCode;
        $hex2 = decbin($m);
        $hex2 = str_rsplit($hex2, 6);
        $hex64 = array();
        foreach($hex2 as $one) {
            $t = bindec($one);
            $hex64[] = $KeyCode[$t];
        }
        $return = preg_replace('/^0*/', '', implode('', $hex64));
        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, '0', STR_PAD_LEFT);
            }
        }
        return $return;
    }

    /**
     *  will 16 The base number string is converted 64 A string of digits in base 
     * @param $m string 16 A string of digits in base 
     * @param $len integer  Returns the length of the string, if insufficient 0 Fill, 0 Is not fill 
     * @return string
     * @author  Wild horses 
     */
    function hex16to64($m, $len = 0) {
        $KeyCode = KeyCode;
        $hex2 = array();
        for($i = 0, $j = strlen($m); $i < $j; ++$i) {
            $hex2[] = str_pad(base_convert($m[$i], 16, 2), 4, '0', STR_PAD_LEFT);
        }
        $hex2 = implode('', $hex2);
        $hex2 = str_rsplit($hex2, 6);
        foreach($hex2 as $one) {
            $hex64[] = $KeyCode[bindec($one)];
        }
        $return = preg_replace('/^0*/', '', implode('', $hex64));
        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, '0', STR_PAD_LEFT);
            }
        }
        return $return;
    }

    /**
     *  Function and PHP The primary function str_split Close, just count the cut from the tail 
     * @param $str string  A string that needs to be cut 
     * @param $len integer  The length of each string 
     * @return array
     * @author  Wild horses 
     */
    function str_rsplit($str, $len = 1) {
        if($str == null || $str == false || $str == '') return false;
        $strlen = strlen($str);
        if($strlen <= $len) return array($str);
        $headlen = $strlen % $len;
        if($headlen == 0) {
            return str_split($str, $len);
        }
        $return = array(substr($str, 0, $headlen));
        return array_merge($return, str_split(substr($str, $headlen), $len));
    }
$a=idate("U");
echo "\r\n<br />e:" . hex10to64($a);
echo "\r\n<br />e:" . hex64to10(hex10to64($a));

2. Algorithm 2:

<?php
$str = "Hello";
echo md5($str);
?>
0
3. Algorithm efficiency test:

View Code 
$strarr = array();
$time1 = microtime(true);
for($i = 0; $i < 10000; ++$i) {
     $str = idate("U")+$i;
     $strarr[] = "{$i}->$str\r\n<br>";
 }
 $time2 = microtime(true);
 $time3 = $time2 - $time1;
 $time1 = microtime(true);
 for($i = 0; $i < 10000; ++$i) {
     $str = dec2s4(idate("U")+$i);
    $strarr[] = "{$i}->$str\r\n<br>";
}
$time2 = microtime(true);
echo "\r\n<br /> run 10000 Times (seconds) : " . ($time2 - $time1 - $time3);

4. Test results
Algorithm 1:0.1687250137329
Algorithm 2:0.044965028762817
5. Conclusion: although algorithm 1 is 1 less efficient, it can convert hexadecimal generated by md5 into hexadecimal generated by md5, and can shorten the string when md5 must be used.

6,
This article covered several methods that can be used to rename uploaded images. The key point is to reduce the string by converting from base 10 to base 64.
For example, the 17-digit number generated using fast_uuid is converted to only 7 characters in hexadecimal 64;
Specific use, can be used flexibly according to their own situation, I hope to help you.

References:

1, GUID baidu encyclopedia: http: / / baike baidu. com view / 185358. htm
2, com_create_guid () official guide: http: / / www php. net manual/zh/function com - create - guid. php
3, MD5 () function description: http: / / www w3school. com. cn/php/func_string_md5 asp
4, time () function description: http: / / www w3school. com. cn/php/func_date_time asp
5, uniqid () function description: http: / / www w3school. com. cn/php/func_misc_uniqid asp


Related articles: