Skip to content

Instantly share code, notes, and snippets.

@fedek6
Created September 11, 2023 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fedek6/97bcb7f9f5fa6ee17bb9958315013462 to your computer and use it in GitHub Desktop.
Save fedek6/97bcb7f9f5fa6ee17bb9958315013462 to your computer and use it in GitHub Desktop.
Generate unique hex string in PHP
<?php
function generate_unique_hex_string($length) {
// Calculate the number of bytes needed for the desired length of the hexadecimal string
$byte_length = ceil($length / 2);
// Generate random bytes
$random_bytes = random_bytes($byte_length);
// Convert the random bytes to a hexadecimal string
$hex_string = bin2hex($random_bytes);
// Get the current timestamp (UNIX timestamp)
$timestamp = time();
// Append the timestamp to the hexadecimal string
$hex_string .= dechex($timestamp);
// Truncate the string to the desired length (if necessary)
$hex_string = substr($hex_string, 0, $length);
return $hex_string;
}
// Example usage:
$unique_hex_string = generate_unique_hex_string(13); // Generates a 16-character hexadecimal string with a timestamp
echo $unique_hex_string;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment