6 Solutions for renaming uploaded images based on php _ PHP Tutorial

Source: Internet
Author: User
Tags idate
A detailed description of the six solutions for renaming uploaded images based on php. I. application scenarios: the auto-increment numbers returned from the database cannot be used to rename the uploaded image. This is determined by the process of uploading images or files. General Image upload process I. application scenarios: the auto-increment numbers returned from the database cannot be used to rename the uploaded image.

This is determined by the process of uploading images or files.
Generally, the image upload process is to upload the image to the server, rename it, and insert it to the database.
That is to say, the self-growth id that is easily obtained in the database cannot be used to rename the uploaded image to avoid duplication of file names,
The method of obtaining the maximum id and 1 from the database increases the number of database connections, which is not applicable to high concurrency and massive data volumes;

II. conventional solutions:

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

Advantage: almost no repetition;
Disadvantage: it is too long to rename the uploaded image.
Usage:

The code is as follows:


/*
Com_create_guid () is a function supported by php5. you can customize unsupported versions by 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 (1, 125 );//"}"
Return $ uuid;
}
}


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

The code is as follows:


$ Str = "Hello ";
Echo md5 ($ str );
?>


Output,

The code is as follows:


8b1a9953c4611296a827abf8c47804d7


Advantage: The output value can be controlled based on the input seed data. if the seed data is regular and does not repeat, md5 can be used to protect the data, resulting in great confusion.
Disadvantage: 32 characters are too long; non-repeated seed data must be provided;
Usage: high concurrency, with the second as the seed data, there will still be duplicates.

The code is as follows:


/*
* Used in combination with the time () function, the number of seconds from January 1, 1970 to the current time is used as the number of seeds.
*/
$ Str = time ();
Echo md5 ($ str );
?>


3, uniqid (): returns a string of 13 or 23 characters.
For our purpose, uniqid () is like the digest version of md5 (). In particular, we can use differential identifiers as the string prefix to reduce the chance of repeated names.
In extreme cases such as non-high concurrency, we recommend that you use this function to meet general requirements.
Detailed description,
Definition: The uniqid () function generates a unique ID based on the current time in microseconds.
Usage: uniqid (prefix, more_entropy)
Note: prefix can be used to add a prefix to the output string. for example, if the more_entropy parameter is true, a 23-bit string is output.

The code is as follows:


Var_dump (uniqid ());
Var_dump (uniqid (""));
?>


Output result:

The code is as follows:


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


Advantage: 13-bit string length, which is an acceptable file name length. you can add a prefix and the result contains data obfuscation, which can prevent the original data from being pushed back.
Disadvantages: Similar to md5, it is highly concurrent, and duplicate data occurs in seconds.

III. upgrade plan:

1, fast_uuid: return 17 digits.
It is a bit like the incomplete customization of uniqid (). The concept of "start time of seeds" in this function is very enlightening.
The default time used in time () and uniqid () is calculated from January 1, 1970, with a length of 10 (1366512439). This value can be reduced using the "seed start time, because what we actually need is only a value that can automatically increase.
After the start time is customized, in addition to reducing the length, it can also be confused.

The code is as follows:


/*
* The suffix_len parameter specifies the number of random numbers appended to the generated ID value. The default value is 3.
* Thanks to the algorithms provided by "Ivan Tan | Tan Junqing DrinChing (at) Gmail.com.
* @ Param int suffix_len
* @ Return string
*/
Function fast_uuid ($ suffix_len = 3 ){
//! Start time for calculating the number of seeds
$ Being_timestamp = strtotime ('2017-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;
}


Output,

The code is as follows:


29832412631099013


2, time () + random number:

In the preceding example, a random number is used to solve multiple requests in one second. Two functions are provided as follows,

The code is as follows:


Function random ($ length ){
$ Hash = '';
$ Chars = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxy ';
$ Max = strlen ($ chars)-1;
PHP_VERSION <'4. 100' & mt_srand (double) microtime () * 2.0 );
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). '000000'): ($ seed. 'zz '. strtoupper ($ seed ));
$ Hash = '';
$ Max = strlen ($ seed)-1;
For ($ I = 0; $ I <$ length; $ I ++ ){
$ Hash. = $ seed [mt_rand (0, $ max)];
}
Return $ hash;
}
?>


IV. Final plan:

Train of Thought: userid + second + random number. The "userid + second" 10-to 64-to-64, reducing the number of digits;

Note:
1. userid: convert the 64-digit maximum value "ZZZZ" to "decimal" equal to "16777215", and "ZZZ" to a decimal maximum value equal to "262143";
2, second: set your own time start point.
$ Less = time ()-strtotime ('2017-4-21 '); convert to 64-digit "1SpRe", 5-bit
$ Less = time ()-strtotime ('1970-3-21 '); convert to 64-digit "_ jHY"; 4-bit
3. random number: use random (3) to generate a three-digit random number;

Final result:
4-digit userid + 4-digit second + 3-digit random number = 11-digit string. Although the results are similar to those of uniqid (), the robustness is improved.

5. Convert decimal to 64-digit algorithm:

1. Algorithm 1:

The code is as follows:


View Code

Const KeyCode = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz _ $ ';

/**
* Convert a 64-digit numeric string to a 10-digit numeric string.
* @ Param $ m string 64-digit numeric string
* @ Param $ len integer returns the length of the string. if the length is not enough, fill the string with 0. if the length is not enough, do not fill the string with 0.
* @ Return string
* @ Author Mustang
*/
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;
}

/**
* Convert a 10-digit numeric string to a 64-digit numeric string.
* @ Param $ m string a 10-digit numeric string
* @ Param $ len integer returns the length of the string. if the length is not enough, fill the string with 0. if the length is not enough, do not fill the string with 0.
* @ Return string
* @ Author Mustang
*/
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;
}

/**
* Convert a hexadecimal numeric string to a 64-digit numeric string.
* @ Param $ m string hexadecimal numeric string
* @ Param $ len integer returns the length of the string. if the length is not enough, fill the string with 0. if the length is not enough, do not fill the string with 0.
* @ Return string
* @ Author Mustang
*/
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;
}

/**
* The function is similar to the PHP native function str_split. it only starts counting and cutting from the end.
* @ Param $ str string the string to be cut
* @ Param $ len integer the length of each string segment
* @ Return array
* @ Author Mustang
*/
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
E: ". hex10to64 ($ );
Echo "\ r \ n
E: ". hex64to10 (hex10to64 ($ ));


2. Algorithm 2:

The code is as follows:


View Code

Function dec2s4 ($ dec ){
$ Base = '1970 _ $ 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 ($ ));
Var_dump (s42dec (dec2s4 ($ )));


3. algorithm efficiency test:

The code is as follows:


View Code

$ Strarr = array ();
$ Time1 = microtime (true );
For ($ I = 0; $ I <10000; ++ $ I ){
$ Str = idate ("U") + $ I;
$ Strarr [] = "{$ I}-> $ str \ r \ n
";
}
$ 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
";
}
$ Time2 = microtime (true );
Echo "\ r \ n
10000 running times (seconds): ". ($ time2-$ time1-$ time3 );


4. test results
Algorithm 1687250137329
Algorithm. 044965028762817
5. Conclusion: Although Algorithm 1 is less efficient, it can convert the hexadecimal format generated by md5 to 64, which can shorten the string in an environment where md5 must be used.

VI. Summary
This article involves several methods that can be used to rename an uploaded image. The key point is to use a 10-in-one conversion to a 64-in-one conversion to reduce the string.
For example, a 17-digit number generated using fast_uuid is converted to a 64-digit number with only 7 characters;
You can use it flexibly based on your own situation. I hope it will 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

Bytes. This is determined by the process of uploading images or files. General Image upload process...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.