PHP Unique random string generator - php

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(), '-', '' ));

Related

PHP random string generator with custom choice

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

How do I generate a list of random strings and hashes and output it in an HTML table?

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);

How to get string of fixed length without using rand() function

How to get a fixed length string without using the rand() function?
I have this but I do not want to use the rand() function
function generateRandomString($length =6) {
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($j = 0; $j < $length; $j++) {
$randomString .= $characters[mt_rand(0, $charactersLength - 1)];
}
return $randomString;
}
<?php
$start=0;$length=6;
$str='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$Val=substr(str_shuffle($str),$start,$length);
echo $Val;
?>
function mt_rand_str ($l, $c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
for ($s = '', $cl = strlen($c)-1, $i = 0; $i < $l; $s .= $c[mt_rand(0, $cl)], ++$i);
return $s;
}
Here you can call this function for 8 character
mt_rand_str(8)
you can use following code to get fixed length random string
<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);
// this will genrate randome string with fixed string lenght
echo $shuffled;
?>

How to generate unique string which in not into specific array?

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;
}

Want to generate random number including quotes

I want to genetate a random number like a,b,c,'and ".So far i have tried
<?php
function generateRandomString($length = 9) {
$char = 'abcd';
$randomString = '';
for ($i = 0; $i <$length; $i++) {
$randomString = $char[rand(0, strlen($char) - 1)];
}
return $randomString;
}
$ran=generateRandomString();
?>
It generates a,b,c,d as random string
But if i try " like $char='abcd"'; then it generates q,u,o,a,& etc.
<?php
function generateRandomString($length = 9) {
$char = 'abcd"\'';
$randomString = '';
for ($i = 0; $i <$length; $i++) {
$randomString = $char[rand(0, strlen($char) - 1)];
}
return $randomString;
}
$ran=generateRandomString();
?>
Here is solution:
$char = 'abcd"\'';
You can escape and pass the quote.
$char = 'abcd\''

Categories