6 examples of php's methods for uploading image renames

  • 2020-11-03 22:02:53
  • OfStack

1. Applicable Scenario:
Unable to rename uploaded image using the self-growing number returned from the database.
This is determined by the process of uploading images or files.
1 general picture upload process is, first upload the picture to the server, after renaming, insert into the database.
In other words, self-growing id, which is easily available in the database, cannot be used to rename uploaded images to avoid duplicate file names,
The method of obtaining the maximum id plus 1 from the database increases the number of database connections, which is not suitable for the case of high concurrency and large amount of data.
2. Routine programme:
1, guid: 32 characters in decimal number 106.
Format: GUID is formatted as "ES12en-ES13en-ES14en-ES15en-ES16en", where each x is a 32-bit decimal number in the range 0-9 or ES18en-ES19en. For example: 6 F9619FF - 8 B86 - D011 - B42D - 00 C04FC964FF GUID value is effective.
Pros: Rarely repeated;
Cons: Too long for renaming uploaded images.
Usage:

/*
    com_create_guid() is php5 The functions supported by the version, for the unsupported version, you can define yourself; 
*/
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 decimal 106. The difference is that guid is generated randomly and md5 needs to be generated based on 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 is regular and does not repeat, md5 can protect the data, causing great confusion.
Faults: 32-bit characters are too long; Non-duplicate seed data should be provided;
Usage: high concurrency, in seconds as the seed data, there will still be repetition.

<?php
/*
* In combination with time() The function is used with 1970 The number of seconds from year to current time is the number of seeds. 
*/
$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 prefix strings with difference identifiers to reduce the chance of duplicate naming.
For extreme cases such as non-high concurrency, this function is recommended and already meets 1 general requirement.
To elaborate,
Definition: the uniqid() function generates a unique ID based on the current time in microseconds.
Usage: uniqid (prefix more_entropy)
Note: prefix can be prefixed to the output string, as shown in the following example. When the more_entropy parameter is true, the 23-bit string will be output.

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

The output result is:
string(13) "51734aa562254" string(14) "a51734aa562257"
Advantage: 13-bit string length, is acceptable file name length; You can prefix the result with data obfuscation to avoid pushing back on the original data.
Disadvantages: similar to md5, high concurrency, in seconds as the seed data, there will still be repetition.
3. Upgraded version:
1, fast_uuid: Returns 17 digits
Somewhat like an incomplete customized version of uniqid(), the concept of "seed count start time" in this function is instructive.
The default time used in time() and uniqid() is calculated from 1970 and has 10 digits (1366512439). Using seed count start time can reduce this number, because what we really need is only one value that can be automatically increased.
In addition to reducing the length, the custom start time can be confusing.

/*
*  parameter  suffix_len The specified   The generated  ID  How many random Numbers are appended to the value? The default value is  3 . 
*  Thank you" Ivan Tan| Tan Junqing  DrinChing (at) Gmail.com "Provided by the algorithm. 
* @param int suffix_len
* @return string
*/
function fast_uuid($suffix_len=3){
    //!  The start time of counting seeds 
    $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 has already occurred in the above example to resolve multiple requests that occur within 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. Among them, "userid+ second" is 10 decimal to 64 decimal, reducing the number of digits;
Description:
userid: The maximum value of "ZZZZ" converted to decimal is "16777215", "ZZZ" converted to decimal is "262143";
Seconds: Set your own time starting point.
$less = time () - strtotime (' 2012-4-21 '); Convert to base 64 "1SpRe", 5 bits
$less = time () - strtotime (' 2013-3-21 '); Convert to base 64 "_jHY"; four
Random number: random(3) was used to generate 3 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-hexadecimal conversion algorithm:
Method 1:

const KeyCode = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
    /**
     *  will 64 Converts a decimal numeric string to 10 A hexadecimal numeric string 
     * @param $m string 64 A hexadecimal numeric string 
     * @param $len integer  Returns the length of the string if the length is not sufficient 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 Converts a decimal numeric string to 64 A hexadecimal numeric string 
     * @param $m string 10 A hexadecimal numeric string 
     * @param $len integer  Returns the length of the string if the length is not sufficient 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 Converts a decimal numeric string to 64 A hexadecimal numeric string 
     * @param $m string 16 A hexadecimal numeric string 
     * @param $len integer  Returns the length of the string if the length is not sufficient 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 counting cut from the tail 
     * @param $str string  String 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));

Method 2:

function dec2s4($dec) {
    $base = '0123456789_$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $result = '';

    do {
        $result = $base[$dec % 64] . $result;
        $dec = intval($dec / 64);
    } while ($dec != 0);

    return $result;
}

function  s42dec($sixty_four) {
    $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,  );
    $result = 0;
    $len = strlen($sixty_four);

    for ($n = 0; $n < $len; $n++) {
        $result *= 64;
        $result += $base_map[$sixty_four{$n}];
    }

    return $result;
}

$a=idate("U");
var_dump(dec2s4($a));
var_dump(s42dec(dec2s4($a)));

Algorithm efficiency test:

$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 Second time (second) : " . ($time2 - $time1 - $time3);

The test results
Algorithm 1:0.1687250137329
Algorithm 2:0.044965028762817
Conclusion: Although algorithm 1 is less efficient, it can convert the hexadecimal generated by md5 to 64, and can use md5 to shorten the string.
6. Summary
This article covers several methods you can use to upload images for renaming, but the key is to use decimal conversion to 64 for string reduction.
For example, using the 17-digit generated by fast_uuid, only seven characters are converted to hexadecimal digits;
Specific use, can use flexibly according to oneself circumstance, hope to be helpful to everybody.

Related articles: