6 solutions for renaming uploaded images based on php _ php instance

Source: Internet
Author: User
Tags idate
This article introduces how to upload and rename images in php. For more information, see 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

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.