Home Backend Development PHP Problem How to upload pictures and change names in php

How to upload pictures and change names in php

Sep 16, 2021 am 10:46 AM
php picture

How to upload pictures and change their names in php: 1. Rename the uploaded pictures through the GUID method; 2. Use the MD5 method; 3. Use the uniqid method; 4. Use the fast_uuid method, etc.

How to upload pictures and change names in php

The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer

How to upload pictures and change the name in php?

6 examples of methods to rename php uploaded images

1. Applicable scenarios:
cannot be used from the database The returned self-increasing number is used to rename the uploaded image.
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.
In other words, 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.
The method of obtaining the maximum ID plus 1 from the database is used. , increases the number of database connections, and is not suitable for situations with high concurrency and huge data volume;
2. Conventional solution:
1, guid: 32-character hexadecimal number.
Format: The format of the GUID is "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 duplication;
Disadvantages: It is still too long for renaming uploaded pictures.
Usage:

The code is as follows:

/*
    com_create_guid()是php5版本支持的功能,对于不支持的版本,可以自己进行定义;
*/
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(125);// "}"
       return $uuid;
   }
}
Copy after login


2, MD5:
will output the same 32-character hexadecimal number as guid, the difference is guid It is generated randomly, and md5 needs to be generated based on the input data.
Example:

The code is as follows:

<?php
$str = "Hello";
echo md5($str);
?>
Copy after login

Output

8b1a9953c4611296a827abf8c47804d7
Copy after login


Advantages: The output can be controlled based on the input seed data Numerical values, if the seed data is regular and non-repeating, the data can be protected through md5, which will cause 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.

The code is as follows:

<?php
/*
*结合time()函数使用,以1970年到当前时间的秒数作为种子数。
*/
$str=time();
echo md5($str);
?>
Copy after login

3, uniqid(): returns a 13 or 23-digit string
For our purposes, uniqid() is like md5() The improved version, in particular, we can use differential identifiers as string prefixes, which can 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)
Description: 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.

The code is as follows:

<?php
var_dump(uniqid());
var_dump(uniqid("a"));
?>
Copy after login

The output result is:

string(13) "51734aa562254" string(14) "a51734aa562257"
Copy after login

Advantages: 13-digit string length is an acceptable file naming length; OK By adding a prefix, the result contains data obfuscation, 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 17 digits
It is a bit like an incomplete customized version of uniqid(), the "seed number start time" that appears in this function "The concept is inspiring.
The default time used in time() and uniqid() is calculated from 1970, and the length is ten digits (1366512439). Using the "seed number starting time" can reduce this value, because we actually need Yes, it is just a value that can grow automatically.
After the starting time is customized, in addition to reducing the length, it can also play a role in confusion.

The code is as follows:

/*
* 参数 suffix_len指定 生成的 ID 值附加多少位随机数,默认值为 3。
* 感谢“Ivan Tan|谭俊青 DrinChing (at) Gmail.com”提供的算法。
* @param int suffix_len
* @return string
*/
function fast_uuid($suffix_len=3){
    //! 计算种子数的开始时间
    $being_timestamp = strtotime(&#39;2013-3-21&#39;);
    $time = explode(&#39; &#39;, microtime());
    $id = ($time[1] - $being_timestamp) . sprintf(&#39;%06u&#39;, substr($time[0], 2, 6));
    if ($suffix_len > 0)
    {
        $id .= substr(sprintf(&#39;%010u&#39;, mt_rand()), 0, $suffix_len);
    }
    return $id;
}
Copy after login

Output,

29832412631099013
Copy after login

2, time() random number:
Random numbers have already appeared in the above example The use is to solve multiple requests that occur in one second. Two functions are provided as follows,

The code is as follows:

<?php
function random($length) {
    $hash = &#39;&#39;;
    $chars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz&#39;;
    $max = strlen($chars) - 1;
    PHP_VERSION < &#39;4.2.0&#39; && 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 < &#39;4.2.0&#39; ? mt_srand((double)microtime() * 1000000) : mt_srand();
    $seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace(&#39;0&#39;, &#39;&#39;, $seed).&#39;012340567890&#39;) : ($seed.&#39;zZ&#39;.strtoupper($seed));
    $hash = &#39;&#39;;
    $max = strlen($seed) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $seed[mt_rand(0, $max)];
    }
    return $hash;
}
?>
Copy after login

4. Final solution:
Idea: userid seconds random number. Among them, "userid seconds" is converted from decimal to 64, reducing the number of digits;
Description:
userid: The maximum value of "ZZZZ" in 64 is converted to decimal equal to "16777215", and the maximum value of "ZZZ" is converted to decimal The value is equal to "262143";
Seconds: Set your own time starting point.
$less=time()-strtotime('2012-4-21′); Convert to hexadecimal "1SpRe", 5 digits
$less=time()-strtotime('2013-3-21 ′); Convert to hexadecimal "_jHY"; 4-digit 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.
5. Algorithm for converting decimal to hexadecimal:
Algorithm 1:

The code is as follows:

const KeyCode = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$&#39;;
    /**
     * 将64进制的数字字符串转为10进制的数字字符串
     * @param $m string 64进制的数字字符串
     * @param $len integer 返回字符串长度,如果长度不够用0填充,0为不填充
     * @return string
     * @author 野马
     */
    function hex64to10($m, $len = 0) {
        $m = (string)$m;
        $hex2 = &#39;&#39;;
        $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, &#39;0&#39;, STR_PAD_LEFT);
        }
        $return = bindec($hex2);
        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, &#39;0&#39;, STR_PAD_LEFT);
            }
        }
        return $return;
    }
    /**
     * 将10进制的数字字符串转为64进制的数字字符串
     * @param $m string 10进制的数字字符串
     * @param $len integer 返回字符串长度,如果长度不够用0填充,0为不填充
     * @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(&#39;/^0*/&#39;, &#39;&#39;, implode(&#39;&#39;, $hex64));
        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, &#39;0&#39;, STR_PAD_LEFT);
            }
        }
        return $return;
    }
    /**
     * 将16进制的数字字符串转为64进制的数字字符串
     * @param $m string 16进制的数字字符串
     * @param $len integer 返回字符串长度,如果长度不够用0填充,0为不填充
     * @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, &#39;0&#39;, STR_PAD_LEFT);
        }
        $hex2 = implode(&#39;&#39;, $hex2);
        $hex2 = str_rsplit($hex2, 6);
        foreach($hex2 as $one) {
            $hex64[] = $KeyCode[bindec($one)];
        }
        $return = preg_replace(&#39;/^0*/&#39;, &#39;&#39;, implode(&#39;&#39;, $hex64));
        if($len) {
            $clen = strlen($return);
            if($clen >= $len) {
                return $return;
            }
            else {
                return str_pad($return, $len, &#39;0&#39;, STR_PAD_LEFT);
            }
        }
        return $return;
    }
    /**
     * 功能和PHP原生函数str_split接近,只是从尾部开始计数切割
     * @param $str string 需要切割的字符串
     * @param $len integer 每段字符串的长度
     * @return array
     * @author 野马
     */
    function str_rsplit($str, $len = 1) {
        if($str == null || $str == false || $str == &#39;&#39;) 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<br />e:" . hex10to64($a);
echo "\r\n<br />e:" . hex64to10(hex10to64($a));
Copy after login

Algorithm 2:

The code is as follows:

function dec2s4($dec) {
    $base = &#39;0123456789_$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;
    $result = &#39;&#39;;
    do {
        $result = $base[$dec % 64] . $result;
        $dec = intval($dec / 64);
    } while ($dec != 0);
    return $result;
}
function  s42dec($sixty_four) {
    $base_map = array ( &#39;0&#39; => 0,    &#39;1&#39; => 1,    &#39;2&#39; => 2,    &#39;3&#39; => 3,    &#39;4&#39; => 4,    &#39;5&#39; => 5,    &#39;6&#39; => 6,    &#39;7&#39; => 7,    &#39;8&#39; => 8,    &#39;9&#39; => 9,    &#39;_&#39; => 10,    &#39;$&#39; => 11,    &#39;a&#39; => 12,    &#39;b&#39; => 13,    &#39;c&#39; => 14,    &#39;d&#39; => 15,    &#39;e&#39; => 16,    &#39;f&#39; => 17,    &#39;g&#39; => 18,    &#39;h&#39; => 19,    &#39;i&#39; => 20,    &#39;j&#39; => 21,    &#39;k&#39; => 22,    &#39;l&#39; => 23,    &#39;m&#39; => 24,    &#39;n&#39; => 25,    &#39;o&#39; => 26,    &#39;p&#39; => 27,    &#39;q&#39; => 28,    &#39;r&#39; => 29,    &#39;s&#39; => 30,    &#39;t&#39; => 31,    &#39;u&#39; => 32,    &#39;v&#39; => 33,    &#39;w&#39; => 34,    &#39;x&#39; => 35,    &#39;y&#39; => 36,    &#39;z&#39; => 37,    &#39;A&#39; => 38,    &#39;B&#39; => 39,    &#39;C&#39; => 40,    &#39;D&#39; => 41,    &#39;E&#39; => 42,    &#39;F&#39; => 43,    &#39;G&#39; => 44,    &#39;H&#39; => 45,    &#39;I&#39; => 46,    &#39;J&#39; => 47,    &#39;K&#39; => 48,    &#39;L&#39; => 49,    &#39;M&#39; => 50,    &#39;N&#39; => 51,    &#39;O&#39; => 52,    &#39;P&#39; => 53,    &#39;Q&#39; => 54,    &#39;R&#39; => 55,    &#39;S&#39; => 56,    &#39;T&#39; => 57,    &#39;U&#39; => 58,    &#39;V&#39; => 59,    &#39;W&#39; => 60,    &#39;X&#39; => 61,    &#39;Y&#39; => 62,    &#39;Z&#39; => 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)));
Copy after login

Algorithm efficiency test:

The code is as follows:

$strarr = array();
$time1 = microtime(true);
for($i = 0; $i < 10000; ++$i) {
     $str = idate("U")+$i;
     $strarr[] = "{$i}->$str\r\n<br>";
 }
 $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<br>";
}
$time2 = microtime(true);
echo "\r\n<br />运行10000次用时(秒):" . ($time2 - $time1 - $time3);
Copy after login

测试结果
算法1:0.1687250137329
算法2:0.044965028762817
结论:算法1虽然效率上差一些,但是可以把md5生成的16进制转化为64进制,能够使用在必须使用md5的环境下缩短字符串。
六、总结
本文涉及了上传图片重命名可以能使用的几种方法,其中关键点是使用10进制转换为64进制来进行字符串的缩减。
例如,使用fast_uuid生成的17位数字,转换为64进制仅有7位字符;
具体使用,可以根据自身情况灵活使用,希望对大家有所帮助。

推荐学习:《PHP视频教程

The above is the detailed content of How to upload pictures and change names in php. For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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.

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: 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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles