Created
February 16, 2014 14:07
-
-
Save Shaz3e/9034728 to your computer and use it in GitHub Desktop.
HOW TO GENERATE RANDOM STRING IN PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo randomString(10); | |
function randomString($length, $type = '') { | |
// Select which type of characters you want in your random string | |
switch($type) { | |
case 'num': | |
// Use only numbers | |
$salt = '1234567890'; | |
break; | |
case 'lower': | |
// Use only lowercase letters | |
$salt = 'abcdefghijklmnopqrstuvwxyz'; | |
break; | |
case 'upper': | |
// Use only uppercase letters | |
$salt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
break; | |
default: | |
// Use uppercase, lowercase, numbers, and symbols | |
$salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; | |
break; | |
} | |
$rand = ''; | |
$i = 0; | |
while ($i < $length) { // Loop until you have met the length | |
$num = rand() % strlen($salt); | |
$tmp = substr($salt, $num, 1); | |
$rand = $rand . $tmp; | |
$i++; | |
} | |
return $rand; // Return the random string | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment