Home Backend Development PHP Tutorial Detailed introduction to 6 solutions to renaming uploaded images based on PHP_PHP Tutorial

Detailed introduction to 6 solutions to renaming uploaded images based on PHP_PHP Tutorial

Jul 21, 2016 pm 03:11 PM
php one upload introduce use picture Scenes based on database method of solve detailed return Be applicable double naming

1. Applicable scenarios: You cannot use the self-increasing number returned from the database to rename uploaded images.

This is determined by the process of uploading images or files.
The general image upload process is to first upload the image to the server, rename it, and then insert it into the database.
That is to say, the self-increasing ID that is very easy to obtain in the database cannot be used to rename uploaded pictures to avoid duplication of file names.
Instead, the maximum ID plus 1 is obtained from the database. , increases the number of database connections, and is not suitable for situations with high concurrency and huge data volume;

2. Conventional plan:

1, guid: 32-character hexadecimal number.
Format: The GUID is in the format "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", where each x is a 32-digit 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;
Disadvantages: It is still too long for renaming uploaded pictures.
Usage:

Copy code The code is as follows:

/*
com_create_guid() is php5 The functions supported by the version can be defined by yourself 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, 12, 4). ,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
return $uuid;
}
}

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

Copy code The code is as follows:
$str = "Hello" ;
echo md5($str);
?>

output,

Copy code The code is as follows ; protection, creating great confusion. Disadvantages: 32-bit characters are too long; non-duplicate seed data needs to be provided;
Usage: High concurrency, with seconds as the seed data, duplication will still occur.


Copy code

The code is as follows:

/** combined with the time() function Use the number of seconds from 1970 to the current time as the seed number. */$str=time();
echo md5($str);
?>


3, uniqid(): return 13 or 23 Bit string.
For our purposes, uniqid() is like an improved version of md5(), especially since we can use differential identifiers as string prefixes to reduce the chance of repeated naming.
For extreme situations such as non-high concurrency, it is recommended to use this function, which can already meet general needs.
Details,
Definition: The uniqid() function generates a unique ID based on the current time in microseconds.
Usage: uniqid(prefix,more_entropy)
Explanation: prefix can add a prefix to the output string. The example is as follows. When the more_entropy parameter is true, a 23-bit string will be output.



Copy code

The code is as follows:

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

The output result is:
Copy code The code is as follows:

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

Advantages: 13-digit string length is an acceptable file naming length; prefixes can be added, and the result contains data confusion, which can avoid back-referencing the original data.
Disadvantages: Similar to md5, high concurrency, using seconds as the seed data, duplication will still occur.

3. Upgraded version plan:

1, fast_uuid: Returns a 17-digit number.
A bit like an incompletely customized version of uniqid(), the concept of "seed number starting time" that appears in this function is very enlightening.
The default time used in time() and uniqid() is calculated from 1970, and the length is ten digits (1366512439). Using the "seed number start time" can reduce this value, because we actually need Yes, it is just a value that can grow automatically.
After customizing the starting time, in addition to reducing the length, it can also play a role in confusion.

Copy code The code is as follows:

/*
* The parameter suffix_len specifies how many random digits are appended to the generated ID value , the default value is 3.
* Thanks to "Ivan Tan | Tan Junqing DrinChing (at) Gmail.com" for providing the algorithm.
* @param int suffix_len
* @return string
*/
function fast_uuid($suffix_len=3){
                                                                                                                                                                        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 The code is as follows:
29832412631099013

2, time()+random number:
In the above example, random numbers have been used to solve multiple requests that occur in one second. Provide two functions as follows,


Copy code The 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()), 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;
}
?>


Fourth, final plan: Idea: userid+second+random number. Among them, "userid+second" is converted from decimal to 64, reducing the number of digits;

Description:

1, userid: The maximum value of "ZZZZ" converted into decimal is equal to "16777215", and the maximum value of "ZZZ" converted into decimal is equal to "262143";
2, seconds: set yourself the starting point of time.
$less=time()-strtotime('2012-4-21'); Convert to hexadecimal "1SpRe", 5 digits
$less=time()-strtotime('2013-3-21 '); Convert to hexadecimal "_jHY"; 4 digits
3, random number: use random(3) to generate a 3-digit random number;

Final result:

4-digit userid + 4-digit second + 3-digit random number = 11-digit string. Although the results look similar to uniqid(), the robustness is improved.

Five, decimal to hexadecimal conversion algorithm:

1, Algorithm 1:


Copy code The code is as follows:

View Code

const KeyCode = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';

    /**
* Convert a 64-digit string to a decimal string
* @param $m string 64-digit string
* @param $len integer Returns the length of the string , if the length is not enough, fill it with 0, 0 means no padding
* @return string
* @author 马野
*/
    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 the decimal numeric string to a 64-digit numeric string
* @param $m string Decimal numeric string
* @param $len integer Returns the string length , if the length is not enough, fill it with 0, 0 means no padding
* @return string
* @author 马野
*/
    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 hexadecimal number string to hexadecimal number string
* @param $m string Hexadecimal number string
* @param $len integer Returns the string length , if the length is not enough, fill it with 0, 0 means no padding
* @return string
* @author 马野
*/
    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, except that the cutting starts from the end
* @param $str string The string to be cut
* @param $len integer The length of each string
* @return array
* @author 马野
*/
    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 "rn
e:" . hex10to64($a);
echo "rn
e:" . hex64to10(hex10to64($a));


2,算法2:
复制代码 代码如下:

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,    '_' => 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)));


3,算法效率测试:
复制代码 代码如下:

View Code

$strarr = array();
$time1 = microtime(true);
for($i = 0; $i < 10000; ++$i) {
     $str = idate("U")+$i;
     $strarr[] = "{$i}->$strrn
";
 }
 $time2 = microtime(true);
 $time3 = $time2 - $time1;

 $time1 = microtime(true);
 for($i = 0; $i < 10000; ++$i) {
     $str = dec2s4(idate("U")+$i);
    $strarr[] = "{$i}->$strrn
";
}
$time2 = microtime(true);
echo "rn
运行10000次用时(秒):" . ($time2 - $time1 - $time3);


4, test results
Algorithm 1: 0.1687250137329
Algorithm 2: 0.044965028762817
5, conclusion: Although Algorithm 1 is less efficient, it can convert the hexadecimal generated by md5 into hexadecimal. , can be used to shorten strings in environments where md5 must be used.

6. Summary
This article involves several methods that may be used to rename uploaded images. The key point is to use decimal to hexadecimal to reduce the string.
For example, the 17-digit number generated by fast_uuid is converted into hexadecimal with only 7 characters;
The specific use can be used flexibly according to your own situation. I hope it will be helpful to everyone.

Reference:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326899.htmlTechArticle1. Applicable scenario: You cannot use the self-increasing number returned from the database to rename the uploaded image. This is determined by the process of uploading images or files. General image upload processing process...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

See all articles