Avatar ·

How to generate a random unique alphanumeric string in PHP?

Hello everyone! I'm a beginner PHP developer and I've encountered a task: I need to create random strings for session identifiers, coupons, and just for unique links. I tried implementing it using `rand()` and concatenation, but I get duplicate or insecure strings. Here's what I wrote: ```php function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } ``` Problems: 1. Sometimes identical strings are generated with frequent calls (e.g., in a loop). 2. I've heard that `rand()` is not cryptographically secure and is predictable. 3. I don't know how to guarantee