A detailed description of the 6 solutions based on PHP upload image renaming _php instances

Source: Internet
Author: User
Tags idate repetition
One, applicable scenario: cannot use the self-growth number returned from the database to rename the uploaded image.

This is determined by the process of picture or file upload.
General image upload process is to upload images to the server, after renaming, inserted into the database.
In other words, the self-growth ID that is very easy to obtain in the database cannot be used to rename the uploaded image to avoid duplication of the file name.
Using the method of obtaining the maximum ID plus 1 from the database increases the number of database connections and does not apply to high concurrency and large data volumes.

Second, the general scheme:

1,guid:32 character hexadecimal number.
Format: The format of the 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, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid GUID value.

Advantages: almost no repetition;
Cons: Renaming an uploaded image is too long.
Usage:
Copy CodeThe code is as follows:
/*
Com_create_guid () is a feature supported by the PHP5 version and can be defined on its own for unsupported versions;
*/
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, 4). $hyphen
. substr ($charid, 4). $hyphen
. substr ($charid, 20,12)
. chr (125);//"}"
return $uuid;
}
}

2,MD5:
As with GUIDs, the 32-character hexadecimal number is output, except that the GUID is randomly generated and MD5 needs to be generated from the input data.
Example
Copy CodeThe code is as follows:
$str = "Hello";
echo MD5 ($STR);
?>

Output
Copy CodeThe code is as follows:
8b1a9953c4611296a827abf8c47804d7

Advantages: Can be based on the input of the seed data to control the output value, if the seed data is not repeated, the data can be protected by MD5, resulting in a great confusion.
Cons: 32 characters are too long, need to provide non-duplicated seed data;
Usage: High concurrency, with seconds as the seed data, will still appear repeated.
Copy CodeThe code is as follows:
/*
* Combined with the time () function, the number of seconds from 1970 to current is the seed count.
*/
$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 if we can use the differential identifier as a string prefix to reduce the chance of duplicate naming occurrences.
For extreme situations such as non-high concurrency, it is recommended to 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)
Description: Prefix can add a prefix to the output string, which, for example, will output a 23-bit string if the More_entropy parameter is true.
Copy CodeThe code is as follows:
Var_dump (Uniqid ());
Var_dump (Uniqid ("a"));
?>

The output is:
Copy CodeThe code is as follows:
String (51734aa562254) string "a51734aa562257"

Pros: 13-bit string length, is acceptable file name length, you can add a prefix, the result contains data confusion, to avoid the reverse of the original data.
Disadvantage: Similar to MD5, high concurrency, in seconds as the seed data, there will still be a repetition phenomenon.

Third, the upgrade version of the program:

1,fast_uuid: Returns a 17-digit number. The
is somewhat like a uniqid (), and the concept of "seed count start time" In this function is instructive.
Time () and uniqid () are used by default in 1970, with a length of 10 bits (1366512439) and a "seed count start time" to narrow this value, because what we actually need is just a value that can be automatically increased. After the
start time is customized, it can be confusing in addition to reducing the length. The
copy Code code is as follows:
/*
* parameter Suffix_len specifies how many bits of random number are attached to the generated ID value, and the default value is 3.
* Thanks to the algorithm provided by Ivan tan| Tan Junqing drinching (at) gmail.com.
* @param int suffix_len
* @return String
*/
Function Fast_uuid ($suffix _len=3) {
//! compute seed start time
$ 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;
}

Output,
Copy code code as follows:
29832412631099013

2,time () + random number:

The use of random numbers has occurred in the previous example in order to resolve multiple requests that occur in one second. There are two functions provided below,
Copy code code as follows:
!--? php function Random ($length) {
$hash = ';
$chars = ' A Bcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz ';
$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 ()), $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;
}
?

Four, final scenario:

Idea: userid+ seconds + random number. Wherein "userid+ seconds" 10 into the system to 64, reducing the number of bits;

Description
1,userid:64 binary Maximum "ZZZZ" is converted to decimal equals "16777215", "ZZZ" is converted to a decimal maximum equal to "262143";
2, seconds: Set your own time starting point.
$less =time ()-strtotime (' 2012-4-21 '); Convert to 64 binary "1SpRe", 5-bit
$less =time ()-strtotime (' 2013-3-21 '); Convert to 64 binary "_jhy"; 4 bits
3, random number: Generate 3-bit random numbers using random (3);

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

Five, decimal turn 64 binary algorithm:

1, Algorithm 1:
Copy the Code code as follows:
View Code

Const KEYCODE = ' 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz_$ ';

/**
* Converts a 64-digit string into a 10-binary numeric string
* @param string of $m string 64 binary
* @param $len Integer Returns the length of the string, if the length is not sufficient with 0 padding, 0 is not populated
* @return String
* @author Mustang
*/
function Hex64to10 ($m, $len = 0) {
$m = (string) $m;
$hex 2 = ";
$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];
$hex 2. = Str_pad (Decbin ($KeyCode [$one]), 6, ' 0 ', str_pad_left);
}
$return = Bindec ($hex 2);

if ($len) {
$clen = strlen ($return);
if ($clen >= $len) {
return $return;
}
else {
Return Str_pad ($return, $len, ' 0 ', str_pad_left);
}
}
return $return;
}

/**
* Converts a 10-digit string into a 64-binary numeric string
* @param string of $m string 10 binary
* @param $len Integer Returns the length of the string, if the length is not sufficient with 0 padding, 0 is not populated
* @return String
* @author Mustang
*/
function Hex10to64 ($m, $len = 0) {
$KeyCode = KeyCode;
$hex 2 = Decbin ($m);
$hex 2 = Str_rsplit ($hex 2, 6);
$hex = Array ();
foreach ($hex 2 as $one) {
$t = Bindec ($one);
$hex 64[] = $KeyCode [$t];
}
$return = preg_replace ('/^0*/', ' ', implode (', $hex 64));
if ($len) {
$clen = strlen ($return);
if ($clen >= $len) {
return $return;
}
else {
Return Str_pad ($return, $len, ' 0 ', str_pad_left);
}
}
return $return;
}

/**
* Converts a 16-digit string into a 64-binary numeric string
* @param string of $m string 16 binary
* @param $len Integer Returns the length of the string, if the length is not sufficient with 0 padding, 0 is not populated
* @return String
* @author Mustang
*/
function Hex16to64 ($m, $len = 0) {
$KeyCode = KeyCode;
$hex 2 = array ();
for ($i = 0, $j = strlen ($m), $i < $j; + + $i) {
$hex 2[] = Str_pad (Base_convert ($m [$i], 2), 4, ' 0 ', str_pad_left);
}
$hex 2 = Implode ("', $hex 2);
$hex 2 = Str_rsplit ($hex 2, 6);
foreach ($hex 2 as $one) {
$hex 64[] = $KeyCode [Bindec ($one)];
}
$return = preg_replace ('/^0*/', ' ', implode (', $hex 64));
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 native function Str_split Close, just start counting cutting from the tail
* @param string to be cut $str string
* @param $len length of each string of integers
* @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 ($a);
echo "\ r \ n
E: ". Hex64to10 (hex10to64 ($a));

2, Algorithm 2:
Copy the Code code as follows:
View Code

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, ' _ ' and ' + ', ' $ ', ' + ', ' a ', ' + ', ' B ' + ', ' c ' + =, ' d ' = The ' f ' = +, ' g ' = +, ' h ' = +, ' i ', ' + ', ' j ', ' + ', ' k ' = ', ' l ', ' = ', ' m ' +, ' n ' =& Gt ' O ', ' P ', ' + ', ' Q ', ' + ', ' r ' +, ' s ', ' + ', ' u ', ' + ', ' V ' =, ' W ' =& Gt The ' x ' = +, ' y ' = +, ' z ' = Panax notoginseng, ' A ', ' = ', ' B ' = ', ' C ' = +, ' D ' = ', ' E ' = ', ' F ' =& Gt The ' G ' = +, ' H ' and ' N ', ' I ' +, ' J ' =, ' K ', ' = ', ' L ', ' + ' Gt The ' P ' = +, ' Q ' = +, ' R ' = +, ' S ' = +, ' T ', ' + ', ' U ' and ' s ', ' V ' = ', ' W ' = ', ' X ' =& Gt , ' Y ' = +, ' 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)));

3, algorithm efficiency test:
Copy CodeThe code is as follows:
View Code

$strarr = Array ();
$time 1 = microtime (true);
for ($i = 0; $i < 10000; + + $i) {
$str = Idate ("U") + $i;
$strarr [] = "{$i}-> $str \ r \ n
";
}
$time 2 = Microtime (true);
$time 3 = $time 2-$time 1;

$time 1 = microtime (true);
for ($i = 0; $i < 10000; + + $i) {
$str = Dec2s4 (Idate ("U") + $i);
$strarr [] = "{$i}-> $str \ r \ n
";
}
$time 2 = Microtime (true);
echo "\ r \ n
Run 10,000 times (seconds): ". ($time 2-$time 1-$time 3);

4, test results
Algorithm 1:0.1687250137329
Algorithm 2:0.044965028762817
5, Conclusion: Algorithm 1 is less efficient, but can convert MD5 generated 16 into 64, and can be used to shorten strings in environments where MD5 must be used.

Vi., summary
This article deals with several methods that can be used to rename an upload image, where the key point is to use a 10 binary conversion to 64 to reduce the string.
For example, a 17-bit number generated using Fast_uuid, converted to 64 binary with only 7 characters;
Specific use, can be used flexibly according to their own situation, I hope to help you.

Reference documents:

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 Article

    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.