Generate Random String in PHP

This article shows you how to generate a random string using built-in PHP function and user-defined function.

Let’s start with built-in PHP function.

The function random_bytes returns a secure random string, therefore, suitable for use with passwords (meaning not for generating passwords but for purposes such as generating salt to increase password strength). Next, we want to convert the returned bytes to use it in string representation, so that, we will use bin2hex function that returns ASCII string of the bytes representation. Also, when we convert bytes to hex (ASCII representation) using bin2hex, the returned string length will be more than the length of the bytes we passed in random_bytes function. If you want to extract a string with certain length, you can use substr function as given in the code. Note that the preceding code only works in PHP 7 and above.

Next, here is our user-defined function,