functiongenerateRandomString($length=10){$characters='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$charactersLength=strlen($characters);$randomString='';for($i=0;$i<$length;$i++){$randomString.=$characters[rand(0,$charactersLength-1)];}return$randomString;}
Output the random string with the call below:// Echo the random string.// Optionally, you can give it a desired string length.echogenerateRandomString();
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* This function uses type hints now (PHP 7+ only), but it was originally
* written for PHP 5 as well.
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @paramint$length How many characters do we want?
* @paramstring$keyspace A string of all possible characters
* to select from
* @returnstring
*/functionrandom_str(int$length=64,string$keyspace='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):string{if($length<1){thrownewRangeException("Length must be a positive integer");}$pieces=[];$max=mb_strlen($keyspace,'8bit')-1;for($i=0;$i<$length;++$i){$pieces[]=$keyspace[random_int(0,$max)];}returnimplode('',$pieces);}
functiongenerateRandomString($length=10){$characters='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';$charactersLength=strlen($characters);$randomString='';for($i=0;$i<$length;$i++){$randomString.=$characters[rand(0,$charactersLength-1)];}return$randomString;}// Echo the random string.// Optionally, you can give it a desired string length.echogenerateRandomString();