In this episode, we dive into generating random numbers and strings in PHP—something that's always important, especially when you need things to be secure (think passwords, tokens, or shuffling cards for a game). Up until PHP 7, people often used things like rand()
or even md5()
to try and get "random" values, but those aren't cryptographically secure and aren't really safe enough for serious use.
Previously, you might have reached for OpenSSL's openssl_random_pseudo_bytes()
or third-party packages like RandomLib. The problem is, they can be a pain to use if the right PHP extensions aren't installed, or if you want your code to run everywhere without extra work.
Thankfully, PHP 7 introduced two handy new functions: random_int()
and random_bytes()
. We walk through how these work, why they're better, and how they make things so much easier. random_int()
gives you a securely generated random integer between two values—great for use cases like shuffling a deck of cards. random_bytes()
lets you grab any number of securely random bytes, which you can then convert into a readable format with bin2hex()
for things like API tokens or unique file names.
We also chat about how these functions work under the hood and what happens if they aren't supported on your system. Plus, there's a reminder to always use the PHP password hashing API if you're dealing with real user passwords, and to keep an eye on documentation for security best practices. It's a practical, code-filled episode that will help you write more secure PHP 7 apps without any third-party fuss!