I want to generate a random password that has the following pattern:
Capital, small, number, dash, capital, small, number, special charachter.
Example:
Ab1-Cd2$
I have put all the special characters in an array that I randomly pick, so I have that part figured out. But I have no clue of how to do the other part. Any suggestion?
this is not the best way, but this will work
<?php
$capital = range ('A','Z');
$small = range ('a','z');
$number = range ('0','9');
$special = array ("#","$","#");
$password = $capital[array_rand($capital)] .
$small[array_rand($small)] .
$number[array_rand($number)] .
"-" .
$capital[array_rand($capital)] .
$small[array_rand($small)] .
$number[array_rand($number)] .
$special[array_rand($special)];
print $password;
You can read about the functions i used here
array_rand
range
Will produce results like:
Tg8-Im1$
Yj3-Xl3#
Cr1-Lv1#
which i guess is your requirement
Please let me know if you want any more help on this.
Use chr() together with a random ascii value out of the range of A-Z, a-b, 0-9.
chr here: http://php.net/manual/en/function.chr.php
ASCII table here: http://www.asciitable.com/
Example: a-z is from 97 to 122.
You don't need to use regex here. You need an array with values of all possible chars that may appear in the password. Then you simply loop over that array and take random key from it.
$chars = array('a', 'b', 'c'); // For example.
$length = 6;
$password = '';
$count = count($chars) - 1;
for ($i = 0; $i < $length; ++$i) {
$password .= $chars[mt_rand(0, $count)];
}
echo $password;
Edit:
There's a neat trick if you need values that are somehow in range. You can use range() function.
For example, here are that function, plus, chr() function to get ASCII chars (from 0x20 to 0x7E).
$chars = range(chr(32), chr(126));
Related
I was trying to make a Alphanumeric string and use it for a unique field in my database , it is not a replacement of the Primary key mind it . The following code is generating a 22 length text but my concern is will it continue to produce unique strings as i might need it for unique identification of the data.
<?php
$len =22;
$rand = substr(str_shuffle(md5(time())),0,$len);
echo $rand;
?>
Use openssl_random_pseudo_bytes - it will Generate a pseudo-random string of bytes
and the bin2hex() function converts a string of ASCII characters to hexadecimal values
It will provide you secure token
bin2hex(openssl_random_pseudo_bytes($length))
I will always include the time() in the resulting string to make sure it's unique, if first 10 characters are all numerical will be acceptable to you:
$rand = substr(time().str_shuffle(md5(time())),0,$len);
The function str_shuffle(md5(time())) is very unlikely to produce same results within a second.
This is the easiest way aside from manually checking the records of the existence of the random string for uniqueness.
You can use php provided method uniqid().
You can try the following:
$random = 'abcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
for ($i = 0; $i < $string_length; $i++) {
$string .= $random [rand(0, strlen($random ) - 1)];
}
$string_length is the length of your desired string.It will continue giving you unique strings.
I'm trying to use CodeIgniter to write up a small program for school which generates a random 'key' every time I click the 'generate' button. Looking to see if there's a way for me to create a function where I can fill up a 14 character array with a random number or letter and then set the array to a variable which I can call upon to display as my generated key.
Any and all help would be much appreciated as I am new to CodeIgniter.
A while back I wrote this function in PHP, it does what it does and gives you some flexibility as well through complexity modifiers, I used a default set of 5 different 'levels' of characters and the length is also variable ofcourse.
I'm just going to chuck it in here and 'try' to explain what is going on as well as I can by comments:
function rsg($length = 10, $complexity = 2) {
//available 'complexity' subsets of characters
$charSubSets = array(
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'0123456789',
'!##$%^&*()_+{}|:">?<[]\\\';,.`~',
'µñ©æáßðøäåé®þüúíóö'
);
// will be filled with subsets from above $charSubsets
$chars = '';
//concact each subset until complexity is reached onto the $chars variable
for ($i = 0; $i < $complexity; $i++)
$chars .= $charSubSets[$i];
//create array containing a single char per entry from the combined subset in the $chars variable.
$chars = str_split($chars);
//define length of array for mt_rand limit
$charCount = (count($chars) - 1);
//create string to return
$string = '';
//idk why I used a while but it won't really hurt you when the string is less than 100000 chars long ;)
$i = 0;
while ($i < $length) {
$randomNumber = mt_rand(0, $charCount); //generate number within array index range
$string .= $chars[$randomNumber]; //get that character out of the array
$i++; //increment counter
}
return $string; //return string created from random characters
}
This is what I currently use and it has satisfied my needs for quite some time now, if anyone reading over this has improvements I'd love to hear them as well!
$a=array(rand(10000000000000, 99999999999999));
is a quick way to get a 14 digit array.
It depends on how random you want it to be. You could specify all characters you want in a $characters string, then just create a string up to $length, picking a random substring of length 1 from the characters string.
What are the requirements?
Do you want it to be as random as possible (This link might be useful)
Are multiple occurrences of one character allowed in one random string?
Here's an example though: PHP random string generator
I am working on Yii. I want to generate 20 digit random keys. I had written a function as -
public function GenerateKey()
{
//for generating random confirm key
$length = 20;
$chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
shuffle($chars);
$password = implode(array_slice($chars, 0, $length));
return $password;
}
This function is generating 20 digit key correctly. But I want the key in a format like
"g12a-Gh45-gjk7-nbj8-lhk8". i.e. separated by hypen. So what changes do I need to do?
You can use chunk_split() to add the hyphens. substr() is used to remove the trailing hyphen it adds, leaving only those hyphens that actually separate groups.
return substr(chunk_split($password, 4, '-'), 0, 24);
However, note that shuffle() not only uses a relatively poor PRNG but also will not allow the same character to be used twice. Instead, use mt_rand() in a for loop, and then using chunk_split() is easy to avoid:
$password = '';
for ($i = 0; $i < $length; $i++) {
if ( $i != 0 && $i % 4 == 0 ) { // nonzero and divisible by 4
$password .= '-';
}
$password .= $chars[mt_rand(0, count($chars) - 1)];
}
return $password;
(Even mt_rand() is not a cryptographically secure PRNG. If you need to generate something that must be extremely hard to predict (e.g. an encryption key or password reset token), use openssl_random_pseudo_bytes() to generate bytes and then a separate function such as bin2hex() to encode them into printable characters. I am not familiar with Yii, so I cannot say whether or not it has a function for this.)
You can use this Yii internal function:
Yii::app()->getSecurityManager()->generateRandomString($length);
I have some strings containing alpha numeric values, say
asdf1234,
qwerty//2345
etc..
I want to generate a specific constant number related with the string. The number should not match any number generated corresponding with other string..
Does it have to be a number?
You could simply hash the string, which would give you a unique value.
echo md5('any string in here');
Note: This is a one-way hash, it cannot be converted from the hash back to the string.
This is how passwords are typically stored (using this or another hash function, typically with a 'salt' method added.) Checking a password is then done by hashing the input and comparing to the stored hash.
edit: md5 hashes are 32 characters in length.
Take a look at other hash functions:
http://us3.php.net/manual/en/function.crc32.php (returns a number, possibly negative)
http://us3.php.net/manual/en/function.sha1.php (40 characters)
You can use a hashing function like md5, but that's not very interesting.
Instead, you can turn the string into its sequence of ASCII characters (since you said that it's alpha-numeric) - that way, it can easily be converted back, corresponds to the string's length (length*3 to be exact), it has 0 collision chance, since it's just turning it to another representation, always a number and it's a little more interesting... Example code:
function encode($string) {
$ans = array();
$string = str_split($string);
#go through every character, changing it to its ASCII value
for ($i = 0; $i < count($string); $i++) {
#ord turns a character into its ASCII values
$ascii = (string) ord($string[$i]);
#make sure it's 3 characters long
if (strlen($ascii) < 3)
$ascii = '0'.$ascii;
$ans[] = $ascii;
}
#turn it into a string
return implode('', $ans);
}
function decode($string) {
$ans = '';
$string = str_split($string);
$chars = array();
#construct the characters by going over the three numbers
for ($i = 0; $i < count($string); $i+=3)
$chars[] = $string[$i] . $string[$i+1] . $string[$i+2];
#chr turns a single integer into its ASCII value
for ($i = 0; $i < count($chars); $i++)
$ans .= chr($chars[$i]);
return $ans;
}
Example:
$original = 'asdf1234';
#will echo
#097115100102049050051052
$encoded = encode($original);
echo $encoded . "\n";
#will echo asdf1234
$decoded = decode($encoded);
echo $decoded . "\n";
echo $original === $decoded; #echoes 1, meaning true
You're looking for a hash function, such as md5. You probably want to pass it the $raw_output=true parameter to get access to the raw bytes, then cast them to whatever representation you want the number in.
A cryptographic hash function will give you a different number for each input string, but it's a rather large number — 20 bytes in the case of SHA-1, for example. In principle it's possible for two strings to produce the same hash value, but the chance of it happening is so extremely small that it's considered negligible.
If you want a smaller number — say, a 32-bit integer — then you can't use a hash function because the probability of collision is too high. Instead, you'll need to keep a record of all the mappings you've established. Make a database table that associates strings with numbers, and each time you're given a string, look it up in the table. If you find it there, return the associated number. If not, choose a new number that isn't used by any of the existing records, and add the new string and number to the table.
I would like to create a random ID like an airline ticket with out any zeros, o's, ones's, or L's. It would be nice if server time was used in the generation process so no two IDs will be the same. How would one do this?
Following the awesome PHP naming scheme:
function generate_airline_ticket_number($length) {
$characters = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
$max = strlen($characters) - 1;
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
return $string;
}
I should submit this to be included into PHP6 ;)
If you're worried about collisions, my approach would be to do an endless loop:
do
{
$random_stuff = generate_airline_ticket_number(10);
} while(check_if_string__is_not_in__the_database($random_stuff));
There is always possibility that generated number will be repeated.
You have to store that generated earlier numbers and always check if currently generated number does not exist.
To generate a random number you can just use int rand ( int $min , int $max )
uniqid() seems perfect, apart from your limitations on letters and numbers. Selecting a great font may mitigate some of your needs, so you have L, a zero with a strike through, etc.
Baring that, you haven't placed any other limitations so what about.
$id = uniqid()
$bad = array("0", "o", "l", "1");
$good = array("-", "#", "&", "$");
$id_clean = str_replace($bad, $good, $id);
The power of uniqid() combined with easily identified characters.
Another option
function genGoodRandString() {
$rnd_id = md5(uniqid(rand(), true)); // get long random id
$bad = array('0','o','1','l','8'); // define bad chars
$fixed = str_replace($bad, '', $rnd_id); // fix
return substr($fixed, 0, 10); // cut to required length
}
Why not just use a hash like MD5? I believe PHP has a md5() function built in. Another good one to use is sha1().
Using both of these hash functions you will end up getting what you don't want so I suggest you run a regex pattern on the hash to replace them with a random letter A-Z.
Oh, and hashes are usually 100% unique.
I guess I learned something new today.