In this tutorial, we will learn how to generate random string in PHP.
PHP random string generator
There are several ways to produce a random string in PHP.
Here are a few examples:
1) Using str_shuffle
and substr
:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
// Example usage:
$randomString = generateRandomString(8);
echo $randomString;
2) Using random_bytes
and bin2hex
(for PHP 7 and above):
function generateRandomString($length = 10) {
return bin2hex(random_bytes($length / 2));
}
// Example usage:
$randomString = generateRandomString(8);
echo $randomString;
3) Using openssl_random_pseudo_bytes
and bin2hex
(for PHP 5 and above):
function generateRandomString($length = 10) {
return bin2hex(openssl_random_pseudo_bytes($length / 2));
}
// Example usage:
$randomString = generateRandomString(8);
echo $randomString;