Home > Backend Development > PHP Tutorial > How to Generate Valid v4 UUIDs in PHP?

How to Generate Valid v4 UUIDs in PHP?

Patricia Arquette
Release: 2024-12-18 09:19:14
Original
535 people have browsed it

How to Generate Valid v4 UUIDs in PHP?

Generating Valid v4 UUIDs in PHP

Determining the correct format for generating valid v4 UUIDs in PHP can be challenging. A UUID (Universally Unique Identifier) must adhere to a specific pattern: "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx," where "y" represents either an 8, 9, A, or B.

Existing Solution and Limitation

One attempted solution involves breaking down the UUID into components and using random number generation for each section. However, it fails to set the "y" value correctly.

Correcting the Function

To rectify this issue, we need to make specific bit manipulations to the generated data. According to RFC 4122 - Section 4.4, the following bits require modification:

  • time_hi_and_version (bits 4-7 of the 7th octet)
  • clock_seq_hi_and_reserved (bits 6 & 7 of the 9th octet)

Updated Function

Here's the updated PHP function that generates valid v4 UUIDs:

function uuidv4()
{
  $data = random_bytes(16);

  $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
  $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    
  return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
Copy after login

Generating Random Data

To generate sufficiently random data, it's recommended to use either openssl_random_pseudo_bytes() or random_bytes() (for PHP 7 and above). For older PHP versions, openssl_random_pseudo_bytes() can be used.

The above is the detailed content of How to Generate Valid v4 UUIDs in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template