PHP – generate secure password

This post will be very short. We must sometimes generate random password in PHP – for example when users create accounts on our service, or we send them new password after reset. Yes, we can do this in many ways, but most of them are bad solutions – we can create function (or method, class) to generate random string from given range, do it manually and try to make all random. But it isn’t random – it must by real secure, we must  use cryptographically secure pseudorandom generator.

Solution is very simple. We can use random_bytes function. It is secure. And we can chhose generated random string length:

// Return 10-length password
$randomPassword = bin2hex(random_bytes(5)); 

And… it’s all. Really. You should not create your custom functions because it isn’t secure. This method is very simple and secure.