How to create a random string in PHP

A random string with length specified as a parameter ($sLength) and having allowable characters in another parameter ($a).

$s = ""; //random string
$sLength = 35; //random string length (you can put any number, you like your string to be in length)

//allowable chars in the wanted random string (add other chars but avoid chars having special meanings to OS)
$a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_';
for($i = 0, $z = strlen($a)-1; $i != $sLength; $i++)
     $x = rand(0,$z);
     $s .= $a{$x};
echo $s;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>