How to get a random string in php?
This tutorial includes several methods of generating a unique, random, alpha-numeric string with PHP.
1. Code:
<?php function getRandomString($length){ $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } $str1 = getRandomString(20); echo $str1; echo "<br>"; $str1 = getRandomString(18); echo $str1; ?>
2. Example:
Input:
getRandomString(20); getRandomString(18);
Output:
0XjUEjHU4ZH2PFSHBdyv Xoe5b4t2m6dTcQWAY7