Generating a random string in PHP: how to do it correctly and securely?
Hello everyone! I'm a beginner PHP developer writing my first site with user registration. I need to generate random tokens for email confirmation and temporary passwords. I found a simple method online, but I'm not sure it's correct.
Here's what I'm currently using:
```php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo generateRandomString(32); // Example: "a3F8kL9mN2..."
```
Problems I see:
1. The `rand()` function — I've read that it's not cryptographically secure.
2. No guarantee
No answers yet.
Log in to leave an answer
Blogs
Working with Databases in C#: PostgreSQL and MongoDB on .NET