How to generate unique identifiers in PHP
Identifier (IDentifier) refers to a symbol used to identify an entity. It has different meanings in different application environments. This article mainly shares with you how to generate unique identifiers in PHP. I hope it can help you.
1. Applicable scenarios
Avoid duplication of file names
2. Conventional solution
2.1 guid
32 character hexadecimal system 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 repetition;
Disadvantages: It is still too long for renaming uploaded pictures.
Usage:
<?php/* 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; } }?>
2.2 MD5
Like guid, it will output a 32-character hexadecimal number. The difference is that guid is randomly generated, and md5 needs to be based on the input data. generate.
< ?php$str = "Hello";echo md5($str);?>
Output:
8b1a9953c4611296a827abf8c47804d7
Advantages: The output value can be controlled based on the input seed data. If the seed data is regular and non-repeating, the data can be protected through md5, resulting in a lot of problems. Great confusion.
Disadvantages: 32-bit characters are too long; non-duplicate seed data needs to be provided; high concurrency, with seconds as the seed data, duplication will still occur.
Usage:
< ?php/* *结合time()函数使用,以1970年到当前时间的秒数作为种子数。 */$str=time();echo md5($str);?>
2.3 uniqid()
Returns a 13 or 23-digit 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.
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.
< ?phpvar_dump(uniqid());var_dump(uniqid("a")); ?>
The output result is:
string(13) “51734aa562254″ string(14) “a51734aa562257″
Advantages: 13-bit string length is an acceptable file naming length; prefixes can be added, and the result contains data confusion, which can avoid reverse inference of the original data.
Disadvantages: Similar to md5, high concurrency, using seconds as the seed data, duplication will still occur.
3. Upgraded version solution
3.1 fast_uuid: Returns 17 digits
It’s a bit like an incomplete customized version of uniqid(). The “seed number starts” that appears in this function The concept of "time" 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 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.
/* * 参数 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(’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
3.2 time()+random number
The use of random numbers has already appeared in the above example, in order to solve the problem of multiple occurrences in one second ask. Two functions are provided as follows,
< ?phpfunction 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; }?>
4. Final solution
Idea: userid+second+random number. Among them, "userid+second" is converted from decimal to 64, reducing the number of digits;
Description:
userid: maximum value in 64 "ZZZZ" converted to decimal equals "16777215", and the maximum value of "ZZZ" converted to decimal equals "262143";
Seconds: Set your own time starting point.
$less=time()-strtotime(’2012-4-21′); 转换为64进制”1SpRe“,5位$less=time()-strtotime(’2013-3-21′); 转换为64进制”_jHY“;4位
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. 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 a 64-digit number with only 7 characters;
The specific use can be used flexibly according to your own situation. I hope it will be helpful to everyone.
Related recommendations:
How to correctly implement PHP to generate unique identifiers
Some rules for PHP variable identifiers
PHP method to generate unique identifiers
The above is the detailed content of How to generate unique identifiers in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

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

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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