Skip to content

Instantly share code, notes, and snippets.

@craiga
Last active August 29, 2015 14:01
Show Gist options
  • Save craiga/fc0aec6cc988d2029928 to your computer and use it in GitHub Desktop.
Save craiga/fc0aec6cc988d2029928 to your computer and use it in GitHub Desktop.
Generate a random string.
<?php
/**
* Generate a random string.
*
* Based on {@link https://gist.github.com/craiga/4075392 a JavaScript function}.
*
* @param $alphabet (optional) The alphabet used to generate a random string.
* @param $minLength (optional) The minimum length of the string. 10 by default.
* @param $maxLength (optional) The maximum length of the string. 20 by default.
*
* @author Craig Anderson <craiga@craiga.id.au>
* @link https://gist.github.com/craiga/fc0aec6cc988d2029928
*/
function randomString($alphabet = null, $minLength = 10, $maxLength = 20) {
if(is_null($alphabet)) {
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}
$s = "";
$alphabetLength = strlen($alphabet);
$length = rand($minLength, $maxLength);
for($i = 0; $i < $length; $i++) {
$s .= substr($alphabet, rand(0, $alphabetLength - 1), 1);
}
return $s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment