Make Random String in PHP
To make a random string in PHP:
- Precise the characters you want to use.
- Make a loop with your wanted string length as a number of iterations.
- Inside the loop, generate a random character and add it to the existing variable with the string.
- After all iterations, get your random string.
Example:
<?php
function randomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo randomString(10);
?>