6 ways to rename a PHP upload image example _php instance

Source: Internet
Author: User
Tags idate repetition
First, the application scenario:
Unable to rename the uploaded image using the self-growth numbers returned from the database.
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 programme:
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
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:
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 17 digits
Somewhat like the uniqid (), the concept of "seed number start Time", which appears 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.
Since the start time customization, in addition to reducing the length, but also can play a role of confusion.
Copy CodeThe 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 "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 number
$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
29832412631099013
2,time () + random number:
The use of random numbers has occurred in the above example in order to resolve multiple requests that occur in one second. Provides two functions as follows,
Copy CodeThe code is as follows:
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 ()), $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;
}
?>

Iv. Final Programme
Idea: userid+ seconds + random number. Wherein "userid+ seconds" 10 into the system to 64, reducing the number of bits;
Description
userid:64 binary Maximum "ZZZZ" is converted to decimal equals "16777215", "ZZZ" is converted to a decimal maximum equal to "262143";
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
Random number: Generates 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 or 10 binary to 64 binary algorithm:
Algorithm 1:
Copy CodeThe code is as follows:
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));

Algorithm 2:
Copy CodeThe code is as follows:
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)));

Algorithm efficiency test:
Copy CodeThe code is as follows:
$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);

Test results
Algorithm 1:0.1687250137329
Algorithm 2:0.044965028762817
Conclusion: The algorithm 1 is less efficient, but it can convert the MD5 generated 16 into 64, and can be used to shorten the string in an environment 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.
  • 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.