Created
September 11, 2023 07:49
-
-
Save fedek6/97bcb7f9f5fa6ee17bb9958315013462 to your computer and use it in GitHub Desktop.
Generate unique hex string in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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