PHP generate a unique string - php

I have an ID column in a table which stores the row ID number (auto increment), For example 1, 2, 3. I want to generated a random and unique string which could contain only numbers, alphabets and dash (-) and underscore (_). The length of string should be 4-6, and it should be unique. Can someone help me how to generate? thanks.

Use this - base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36), but check new value against db.

function random_gen($length)
{
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890-_";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$random_string = random_gen(6); //This will return a random 6 character string
Above function will generate the unique string

Try this
function genRandomString($length) {
$characters = ’0123456789abcdefghijklmnopqrstuvwxyz-_’;
$string = ”;
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
Call the function with the length you want

Related

Random string rules

I have a function that generates a random 3-character alpha-numeric string. I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random.
function generate_random($length = 3) {
$characters = '123456789ABCDEFGHJKLMNPRSTUVWXYZ';
$rand_str = '';
for ($p = 0; $p < $length; $p++) {
$rand_str .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $rand_str;
}
I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random. How do I do that?
I would personally do it this way:
function generate_random($countAlpha = 2, $countNumeric = 2, $randomize = true) {
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$numeric = '123456789';
$rand_str = '';
for ($p = 0; $p < $countAlpha; $p++) {
$rand_str .= $alpha[mt_rand(0, strlen($alpha)-1)];
}
for ($p = 0; $p < $countNumeric; $p++) {
$rand_str .= $numeric[mt_rand(0, strlen($numeric)-1)];
}
if($randomize) {
$rand_str = str_split($rand_str);
shuffle($rand_str);
return implode($rand_str);
}
return $rand_str;
}
Inside I have 2 for loops, each one based on parameters $countAlpha and $countNumeric. I also have a 3rd parameter, $randomize that will allow you to randomize the output if you wish.
You could separe numbers and letter. Then, append N values of each into an array, shuffle it, and the implode to get your string:
function generate_random($nNumbers = 2, $nAlpha = 2) {
// prepare data to use
$num = '123456789';
$numlen = strlen($num) - 1;
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$alphalen = strlen($alpha) - 1;
$out = []; // New array
// generate N numbers
for ($i = 0; $i < $nNumbers ; $i++) {
$out[] = $num[mt_rand(0, $numlen)];
}
// generate N letters
for ($i = 0; $i < $nAlpha ; $i++) {
$out[] = $alpha[mt_rand(0, $alphalen)];
}
shuffle($out); // Shuffle the array
return implode($out); // Convert to string
}
echo generate_random() ;
// echo generate_random(2, 4) ; // example

How to create 6 digit OTP with 2 digits and 4 alphabets?

I have a script which generates 6 character One Time Password (OTP).
Here is the code:-
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 6) as $k)
$rand .= $seed[$k];
$feedID = $rand;
Now, due to shuffling procedure, currently all 6 can be digits, all 6 can be alphabets.
I want min and max 2 mandatory digits.
How can I do that?
Here's my take on it:
// Create a string of all alpha characters and randomly shuffle them
$alpha = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
// Create a string of all numeric characters and randomly shuffle them
$numeric = str_shuffle('0123456789');
// Grab the 4 first alpha characters + the 2 first numeric characters
$code = substr($alpha, 0, 4) . substr($numeric, 0, 2);
// Shuffle the code to get the alpha and numeric in random positions
$code = str_shuffle($code);
If you want the possibility to have any character more than once, change the two first lines (quick and dirty):
// Let's repeat this string 4 times before shuffle, since we need 4 characters
$alpha = str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4));
// Let's repeat this string 2 times before shuffle, since we need 2 numeric characters
$numeric = str_shuffle(str_repeat('0123456789', 2));
Not saying that this is the best way of doing it, but it's simple, without loops and/or arrays. :)
One more option.
Not saying that this is the best way of doing it, but it's simple, with loops and arrays. ;)
foreach ([4 => range('A', 'Z'), 2 => range(0, 9)] as $n => $chars) {
for ($i=0; $i < $n; $i++) {
$otp[] = $chars[array_rand($chars)];
}
}
shuffle($otp);
$otp = implode('', $otp);
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$seed2= str_split('0123456789');
$rand = [];
for($i=mt_rand(1,2);$i<=2;$i++){
shuffle($seed2);
$rand[]=$seed2[0];
}
while(count($rand)!=6){
shuffle($seed);
$rand[]=$seed[0];
}
shuffle($rand);
print $feedID = implode('',$rand);
you can use random() also to genarate the string with num + letters.LINK
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Hope this help you
function generateRandomString($length = 10,$char_len=4,$numbre_len=2) {
$characters = '0123456789';
$characters2='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$charactersLength2 = strlen($characters);
$randomString = '';
for ($i = 0; $i <$char_len ; $i++) {
$randomString .= $characters2[rand(0, $charactersLength2 - 1)];
}
for ($i = 0; $i <$numbre_len ; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$shuffled = str_shuffle($randomString);
return $shuffled;
}
$length=7;
$char_len=6;
$numbre_len=1;
echo generateRandomString($length,$char_len,$numbre_len);
This function may help to generate dynamic random otp which you want.

Generate Random Password without these characters "l1o0"

I need to generate random password with condition:
All characters are allowable except "l1o0"
Length of 8 to 12 in characters
Codes I've tried:
function generateRandomPassword() {
//Initialize the random password
$password = '';
//Initialize a random desired length
$desired_length = rand(8, 12);
for($length = 0; $length < $desired_length; $length++) {
//Append a random ASCII character (including symbols)
$password .= chr(rand(32, 126));
}
return $password;
}
How to avoid these 4 characters => "l1o0" ?
Reason:
These 4 characters are sometimes confused the user.
Thanks!
Please don't use any of the other answers currently provided for generating passwords. They're not secure by any measure.
rand() -> No
mt_rand() -> Definitely not
I'm going to pull this solution from a blog post aptly titled How to Securely Generate Random Strings and Integers in PHP.
/**
* Note: See https://paragonie.com/b/JvICXzh_jhLyt4y3 for an alternative implementation
*/
function random_string($length = 26, $alphabet = 'abcdefghijklmnopqrstuvwxyz234567')
{
if ($length < 1) {
throw new InvalidArgumentException('Length must be a positive integer');
}
$str = '';
$alphamax = strlen($alphabet) - 1;
if ($alphamax < 1) {
throw new InvalidArgumentException('Invalid alphabet');
}
for ($i = 0; $i < $length; ++$i) {
$str .= $alphabet[random_int(0, $alphamax)];
}
return $str;
}
Usage:
// Every ASCII alphanumeric except "loIO01":
$alphabet = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$string = random_string(12, $alphabet);
You probably don't have random_int(), unless you're reading this in the future when PHP 7 is released. For those of us living in the present, use random_compat.
Try this:
function generateRandomPassword($length = 8) {
$characters = '23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomPassword = '';
for ($i = 0; $i < $length; $i++) {
$randomPassword .= $characters[rand(0, $charactersLength - 1)];
}
return $randomPassword;
}
You don't need to change your code . just use str_replace to replace those word's You can try this solution :) . Just edited your code
function generateRandomPassword($length = 8) {
$characters = '23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomPassword = '';
for ($i = 0; $i < $length; $i++) {
$randomPassword .= $characters[rand(0, $charactersLength - 1)];
}
return str_replace(['l','1','o','0'], ['A','B','C','D'], $randomPassword);
}
$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$req_pword_len = 20;
$char_count = 0;
$password='';
$chars=str_split($string);
while ( $char_count < $req_pword_len ) {
$char = mt_rand(0,61);
$password .= (string) $chars[$char];
$char_count++;
}
Change the value for
$string to be just the characters you want to allow
$req_pword_len to the required length of the password
Try this:
function generateRandomPassword($length = 8) {
$randomPassword = '';
for ($i = 0; $i < $length; $i++) {
while (true) {
//remove 0,1,I,O,l,o
while(in_array(($number = rand(65, 122)), array(48, 49, 73, 79, 108, 111)));
if ($number <= 90 or $number >= 97) {
$randomPassword .= chr($number);
break ;
}
}
}
return $randomPassword;
}
echo generateRandomPassword();

Creating a random estimate string in php

I need to create a auto incrementing string similar to this randomly via php. The string is like this. So what i need is a mix of numbers and letter that is randomally generated and doesnt have to be sequential just as long as its random like this 823N9823 and it has 8 characters max
If the characters don't need to be unique:
function randomString($length = 8, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
$randomString = '';
$numofChars = strlen($chars);
while (--$length) {
$randomString .= $chars[mt_rand(0, $numofChars - 1)];
}
return $randomString;
}
If the characters must be unique:
function randomString($length = 8, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') {
return substr(str_shuffle($chars), 0, 8);
}
usage:
echo generateRandomName();
function:
function generateRandomName($length=8,$level=2){
list($usec, $sec) = explode(' ', microtime());
srand((float) $sec + ((float) $usec * 100000));
$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$validchars[3] = "0123456789_!##$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!##$%&*()-=+/";
$password = "";
$counter = 0;
while ($counter < $length) {
$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
// All character must be different
if (!strstr($password, $actChar)) {
$password .= $actChar;
$counter++;
}
}
return $password;
}
Found on PHPToys
Level the level of characters to be used, 3 have special chars as $validchars[3] has.
You also can call it as: generateRandomName(5) to generate a name with length of 5.
function generateRandomString($length=8, $characters='abcdefghijklmnopqrstuvwxyz0123456789'){
$str = '';
$len = strlen($characters);
for($i=0; $i<length; $i++){
$str .= $characters[mt_rand(0, $len)];
}
return $string;
}
Usage:
//generates a random string, using defaults: length = 8 and characters = a-z, 0-9
echo "Your password: " . generateRandomString();
//custom length: 10
echo "Thingeys: " . generateRandomString(10);
//digits only, length 4
echo "Your PIN: " . generateRandomString(4, '0123456789');
You can use mt_rand() to generate a random integer and then transform the values into a string. The function below will give you 2 821 109 907 456 possible values.
function random_id($length = 8) {
$validChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rndString = '';
for($i = 0; $i < $length; $i++) {
$rndString .= $validChars[mt_rand(0, strlen($validChars) - 1)];
}
return $rndString;
}
$lengthEight = random_id();
$lengthTen = random_id(10);
Since there are more letters and numbers in the list of possible characters, you'll usually get a string with more letters then numbers.
If you want to skew the results towards a string with more numbers then letters, then you can use the following:
function skewed_random_id($numericFactor = 0.8, $length = 8) {
$validAlpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$validNumeric = '0123456789';
$rndString = '';
for($i = 0; $i < $length; $i++) {
if((mt_rand() / mt_getrandmax()) < $numericFactor) {
$rndString .= $validNumeric[mt_rand(0, strlen($validNumeric) - 1)];
} else {
$rndString .= $validAlpha[mt_rand(0, strlen($validAlpha) - 1)];
}
}
return $rndString;
}
$eightyPercentNumeric = skewed_random_id();
$fiftyFifty = skewed_random_id(0.5);
$allAlpha = skewed_random_id(0);
$allNumeric = skewed_random_id(1);
echo substr(str_replace(array('/', '+'), '', base64_encode(sha1(uniqid(), true))), 0, 8);
Sample output:
LTeQpy9p
v11oy9R7
TjdkXZru
lh3TvNi4
X5Ca0ZXS
L01RfhxW
QDfwNnGO
you can use strtoupper and strtolower to get a version that suits your needs.
EDIT:
If you are gonna use this for something critical rather than just wanting a random string, change uniqid() into mt_rand():
echo substr(str_replace(array('/', '+'), '', base64_encode(sha1(
mt_rand(). '.'. mt_rand(). '.'. mt_rand()%4 //256^8 of input possibilities (8 bytes)
, true))), 0, 8);
substr(uniqid(), 0, 8);
http://php.net/uniqid

Generating (pseudo)random alpha-numeric strings

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
$random_string_length is the length of the random string.
I like this function for the job
function randomKey($length) {
$pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $pool[mt_rand(0, count($pool) - 1)];
}
return $key;
}
echo randomKey(20);
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.
function randomString($length)
{
return bin2hex(random_bytes($length));
}
One line solution:
echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );
You can change the substr parameter in order to set a different length for your string.
Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
See More:
chr function
mt_rand function
I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:
class RandomString
{
private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
private static $string;
private static $length = 8; //default random string length
public static function generate($length = null)
{
if($length){
self::$length = $length;
}
$characters_length = strlen(self::$characters) - 1;
for ($i = 0; $i < self::$length; $i++) {
self::$string .= self::$characters[mt_rand(0, $characters_length)];
}
return self::$string;
}
}
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned
Maybe I missed something here, but here's a way using the uniqid() function.
I have made the following quick function just to play around with the range() function. It just might help someone sometime.
Function pseudostring($length = 50) {
// Generate arrays with characters and numbers
$lowerAlpha = range('a', 'z');
$upperAlpha = range('A', 'Z');
$numeric = range('0', '9');
// Merge the arrays
$workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
$returnString = "";
// Add random characters from the created array to a string
for ($i = 0; $i < $length; $i++) {
$character = $workArray[rand(0, 61)];
$returnString .= $character;
}
return $returnString;
}
You can use the following code. It is similar to existing functions except that you can force special character count:
function random_string() {
// 8 characters: 7 lower-case alphabets and 1 digit
$character_sets = [
["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
["count" => 1, "characters" => "0123456789"]
];
$temp_array = array();
foreach ($character_sets as $character_set) {
for ($i = 0; $i < $character_set["count"]; $i++) {
$random = random_int(0, strlen($character_set["characters"]) - 1);
$temp_array[] = $character_set["characters"][$random];
}
}
shuffle($temp_array);
return implode("", $temp_array);
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
echo generateRandomString();
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
First list the desired characters
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.
$alpha=substr(str_shuffle($chars), 0, 50);
50 is the Length of string.
This is something I use:
$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);
You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here
Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().
<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
for($i = 0; $i < 6; $i++) {
$string .= $character_array[rand(0, (count($character_array) - 1))];
}
echo $string;
?>
This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().
1 line:
$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
The modern way to do that with type hint / rand_int for real randomeness
function random_string(int $size): string
{
$characters = array_merge(
range(0, 9),
range('A', 'Z')
);
$string = '';
$max = count($characters) - 1;
for ($i = 0; $i < $size; $i++) {
$string .= $characters[random_int(0, $max)];
}
return $string;
}
public function randomString($length = 8)
{
$characters = implode([
'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
'abcdefghijklmnoprqstuwvxyz',
'0123456789',
//'!##$%^&*?'
]);
$charactersLength = strlen($characters) - 1;
$string = '';
while ($length) {
$string .= $characters[mt_rand(0, $charactersLength)];
--$length;
}
return $string;
}

Categories