PHP - Generate Random Strings

Comments

Generating random strings in PHP is, in my opinion, not as nice as in Bash or Python, however here is how to do it.

<?php

// Alphanumeric characters
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

// Alphanumeric + special characters
$charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890;,.'|[]{}()=+-_`!@#%^&*:'?<>";

$charSetSize = strlen($charSet); $pwdSize = 20;
$pwd = '';

for ($i = 0; $i < $pwdSize; $i++) {
  $pwd .= $charSet[ mt_rand( 0, strlen($charSetSize) - 1 ) ];
}

echo $pwd;

?>

Examples

Alphanumeric: x7T8YMtbAzbWmf5eex6fI Special characters: 7.=Z&19}.{P|{GEqT+d3w

Next Post
3 Simple Server Changes to Boost Website Performance

Previous Post
Postfix - Pipe Emails to a Script


comments powered by Disqus