I'm trying to make a "special" string generator, with a custom selection for which characters you want.
shortly in the code when you call this function:
generateRandomString(length, [special characters], [numbers], [lower characters], [upper characters]);
for example:
generateRandomString(5, true, true, true, true);
the code should be max 5 characters, with letters, numbers and special characters... like: fE3%!
but is gives me 5 random string for each bool active so if it 4 I have back 20 characters instead of 5
this is the code, what am I doing wrong?
function generateRandomString($length, $special, $numbers, $upper, $lower)
{
//$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters["special"] = "!%";
$characters["numbers"] = "01";
$characters["upper"] = "ABC";
$characters["lower"] = "abc";
$randomString = '';
for ($i = 0; $i < $length; $i++)
{
if($special)
{
$randomString .= $characters["special"][rand(0, strlen($characters["special"]) - 1)];
}
if($numbers)
{
$randomString .= $characters["numbers"][rand(0, strlen($characters["numbers"]) - 1)];
}
if($upper)
{
$randomString .= $characters["upper"][rand(0, strlen($characters["upper"]) - 1)];
}
if($lower)
{
$randomString .= $characters["lower"][rand(0, strlen($characters["lower"]) - 1)];
}
}
return $randomString;
}
You should first build valid characters range based on given parameters, and only then build random string.
Added validator to ensure that at least one character from each required group exists in random string.
function generateRandomString($length, $special, $numbers, $upper, $lower)
{
//$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters["special"] = "!%";
$characters["numbers"] = implode('', range(0, 9));
$characters["upper"] = implode('', range('A', 'Z'));
$characters["lower"] = implode('', range('a', 'z'));
$charactersSet = '';
$validators = [];
$randomString = '';
if ($special) {
$charactersSet .= $characters["special"];
$validators[] = '/[' . preg_quote($characters["special"]) . ']/';
}
if ($numbers) {
$charactersSet .= $characters["numbers"];
$validators[] = '/\d/';
}
if ($upper) {
$charactersSet .= $characters["upper"];
$validators[] = '/[A-Z]/';
}
if ($lower) {
$charactersSet .= $characters["lower"];
$validators[] = '/[a-z]/';
}
for ($i = 0; $i < $length; $i++) {
$randomString .= $charactersSet[rand(0, strlen($charactersSet) - 1)];
}
foreach ($validators as $pattern) {
if (preg_match($pattern, $randomString) === 0) {
$randomString = generateRandomString($length, $special, $numbers, $upper, $lower);
break;
}
}
return $randomString;
}
This solution picks a random range of characters on each iteration, then picks a random letter from that range of characters.
function generateRandomString($length, $special, $numbers, $upper, $lower)
{
$alphabet = [
'`~!##$%^&*()_+-=[]{};\':",./<>?',
'0123456789',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'
];
$allowable = [];
if ($special)
$allowable[] = 0;
if ($numbers)
$allowable[] = 1;
if ($upper)
$allowable[] = 2;
if ($lower)
$allowable[] = 3;
$output = '';
for ($i = 0; $i < $length; ++$i) {
$which = $allowable[array_rand($allowable)];
$alphabet_size = strlen($alphabet[$which])-1;
$rand_character = rand(0, $alphabet_size);
$output .= $alphabet[$which][$rand_character];
}
return $output;
}
try to change the for loop to while loop like this :
function generateRandomString($length, $special, $numbers, $upper, $lower)
{
//$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characters["special"] = "!%";
$characters["numbers"] = "01";
$characters["upper"] = "ABC";
$characters["lower"] = "abc";
$randomString = '';
while(strlen($randomString) <= $length)
{
if($special)
{
$randomString .= $characters["special"][rand(0, strlen($characters["special"]) - 1)];
}
if($numbers && strlen($randomString) <= $length)
{
$randomString .= $characters["numbers"][rand(0, strlen($characters["numbers"]) - 1)];
}
if($upper && strlen($randomString) <= $length)
{
$randomString .= $characters["upper"][rand(0, strlen($characters["upper"]) - 1)];
}
if($lower && strlen($randomString) <= $length)
{
$randomString .= $characters["lower"][rand(0, strlen($characters["lower"]) - 1)];
}
}
return $randomString;
}
Updated :
(for exemple the length equel to 5)
for while not breaked if we don't have 5 steps
while loop for every step check if the string length not 5
also checking for every nested condition if the string has equel to 5
Related
How to make a random string unique to the string in the column below?
<?php
$n=10;
function getName($n) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i++) {
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
echo getName($n);
?>
<?php
$n = 10;
function getName($n) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $n; $i++) {
$index = rand(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}
return $randomString;
}
function getUniqueString($length, $dbConnection){
$string = getName($length);
$count = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
while($count != 0){
$string = getName($length);
$count = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
}
return $string;
}
echo getUniqueString($n, $dbConnection);
?>
You can use openssl_random_pseudo_bytes() or random_bytes() PHP fonction to generate random strings.
You can also rely on MySQL to generate uniq IDs :
INSERT INTO mytable (alphaID) VALUES (REPLACE( UUID(), '-', '' ));
I'm trying to generate a list of, let's say 10, random strings and it's SHA-256 hash in an HTML table.
I have found the following code submitted by another user to generate the random string:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
How do I loop the function and how do I output the string and the hash of the string in an HTML table?
Try this code:
<?php
function generate($length)
{
$string = '';
if($length > 128)
{
$string .= generate($length-128);
}
else
{
$string = substr(hash('sha512',mt_rand()),0,$length);
}
return $string;
}
$table = '<table>%s</table>';
$item = '<tr><td>%s</td><td>%s</td></tr>';
$res = '';
for($i=0;$i<10;$i++)
{
$str = generate(10);
$hash = hash('sha256', $str);
$res .= sprintf($item, $hash, $str);
}
echo sprintf($table, $res);
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();
I want to generate unique string.
My code is:
function string(){
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$str= '';
for ($i = 0; $i < 3; $i++) {
$str.= $characters[rand(0, strlen($characters) - 1)];
}
return $str;
}
above code through I'm Generate unique string but that string must not in below array
$array = array('adc','Fs5','sf9','9Sf', ..........);
Anyone know how to do this?
$array = array('adc','Fs5','sf9','9Sf', ..........);
function string() {
global $array;
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
do {
$str= '';
for ($i = 0; $i < 3; $i++) {
$str.= $characters[rand(0, strlen($characters) - 1)];
}
} while (in_array($str, $array));
return $str;
}
I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.