Generate random 5 characters string - php

I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.

$rand = substr(md5(microtime()),rand(0,26),5);
Would be my best guess--Unless you're looking for special characters, too:
$seed = str_split('abcdefghijklmnopqrstuvwxyz'
.'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.'0123456789!##$%^&*()'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
Example
And, for one based on the clock (fewer collisions since it's incremental):
function incrementalHash($len = 5){
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$base = strlen($charset);
$result = '';
$now = explode(' ', microtime())[1];
while ($now >= $base){
$i = $now % $base;
$result = $charset[$i] . $result;
$now /= $base;
}
return substr($result, -5);
}
Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")

If for loops are on short supply, here's what I like to use:
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);

You can try it simply like this:
$length = 5;
$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25

A speedy way is to use the most volatile characters of the uniqid function.
For example:
$rand = substr(uniqid('', true), -5);

The following should provide the least chance of duplication (you might want to replace mt_rand() with a better random number source e.g. from /dev/*random or from GUIDs):
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$result = '';
for ($i = 0; $i < 5; $i++)
$result .= $characters[mt_rand(0, 61)];
?>
EDIT:
If you are concerned about security, really, do not use rand() or mt_rand(), and verify that your random data device is actually a device generating random data, not a regular file or something predictable like /dev/zero. mt_rand() considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php
EDIT:
If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():
<?php
$length = 5;
$randomBytes = openssl_random_pseudo_bytes($length);
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$result = '';
for ($i = 0; $i < $length; $i++)
$result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>

I always use the same function for this, usually to generate passwords. It's easy to use and useful.
function randPass($length, $strength=8) {
$vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz';
if ($strength >= 1) {
$consonants .= 'BDGHJLMNPQRSTVWXZ';
}
if ($strength >= 2) {
$vowels .= "AEUY";
}
if ($strength >= 4) {
$consonants .= '23456789';
}
if ($strength >= 8) {
$consonants .= '##$%';
}
$password = '';
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}

It seems like str_shuffle would be a good use for this.
Seed the shuffle with whichever characters you want.
$my_rand_strng = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), -5);

I also did not know how to do this until I thought of using PHP array's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:
function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
$letters = str_split($abc);
$str = "";
for ($i=0; $i<=$len; $i++) {
$str .= $letters[rand(0, count($letters)-1)];
};
return $str;
};
You can use this function like this
randstr(20) // returns a random 20 letter string
// Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"

$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
//97 is ascii code for 'a' and 122 is ascii code for z
$str .= chr(rand(97, 122));
}
return $str

Similar to Brad Christie's answer, but using sha1 alrorithm for characters 0-9a-zA-Z and prefixed with a random value :
$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);
But if you have set a defined (allowed) characters :
$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);
$str = '';
for ($i=0; $i<5; $i++) {
$str .= $validChars[rand(0,$validCharsCount - 1)];
}
** UPDATE **
As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.

If it's fine that you'll get only letters A-F, then here's my solution:
str_pad(dechex(mt_rand(0, 0xFFFFF)), 5, '0', STR_PAD_LEFT);
I believe that using hash functions is an overkill for such a simple task as generating a sequence of random hexadecimal digits. dechex + mt_rand will do the same job, but without unnecessary cryptographic work. str_pad guarantees 5-character length of the output string (if the random number is less than 0x10000).
Duplicate probability depends on mt_rand's reliability. Mersenne Twister is known for high-quality randomness, so it should fit the task well.

works fine in PHP (php 5.4.4)
$seed = str_split('abcdefghijklmnopqrstuvwxyz');
$rand = array_rand($seed, 5);
$convert = array_map(function($n){
global $seed;
return $seed[$n];
},$rand);
$var = implode('',$convert);
echo $var;
Live Demo

Source: PHP Function that Generates Random Characters
This simple PHP function worked for me:
function cvf_ps_generate_random_code($length=10) {
$string = '';
// You can define your own characters here.
$characters = "23456789ABCDEFHJKLMNPRTVWXYZabcdefghijklmnopqrstuvwxyz";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
Usage:
echo cvf_ps_generate_random_code(5);

Here are my random 5 cents ...
$random=function($a, $b) {
return(
substr(str_shuffle(('\\`)/|#'.
password_hash(mt_rand(0,999999),
PASSWORD_DEFAULT).'!*^&~(')),
$a, $b)
);
};
echo($random(0,5));
PHP's new password_hash() (* >= PHP 5.5) function is doing the job for generation of decently long set of uppercase and lowercase characters and numbers.
Two concat. strings before and after password_hash within $random function are suitable for change.
Paramteres for $random() *($a,$b) are actually substr() parameters. :)
NOTE: this doesn't need to be a function, it can be normal variable as well .. as one nasty singleliner, like this:
$random=(substr(str_shuffle(('\\`)/|#'.password_hash(mt_rand(0,999999), PASSWORD_DEFAULT).'!*^&~(')), 0, 5));
echo($random);

function CaracteresAleatorios( $Tamanno, $Opciones) {
$Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
$Tamanno = empty($Tamanno) ? 16 : $Tamanno;
$Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
$Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
$CantidadCaracteres=strlen($Caracteres)-1;
$CaracteresAleatorios='';
for ($k = 0; $k < $Tamanno; $k++) {
$CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
}
return $CaracteresAleatorios;
}

I`ve aways use this:
<?php function fRand($len) {
$str = '';
$a = "abcdefghijklmnopqrstuvwxyz0123456789";
$b = str_split($a);
for ($i=1; $i <= $len ; $i++) {
$str .= $b[rand(0,strlen($a)-1)];
}
return $str;
} ?>
When you call it, sets the lenght of string.
<?php echo fRand([LENGHT]); ?>
You can also change the possible characters in the string $a.

Simple one liner which includes special characters:
echo implode("", array_map(function() {return chr(mt_rand(33,126));}, array_fill(0,5,null)));
Basically, it fills an array with length 5 with null values and replaces each value with a random symbol from the ascii-range and as the last, it joins them together t a string.
Use the 2nd array_fill parameter to control the length.
It uses the ASCII Table range of 33 to 126 which includes the following characters:
!"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Related

Reverse string without strrev

Some time ago during a job interview I got the task to reverse a string in PHP without using strrev.
My first solution was something like this:
$s = 'abcdefg';
$temp = '';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$temp .= $s{$length - $i - 1};
}
var_dump($temp);
// outputs string(7) "gfedcba"
then they asked me if I could do this without doubling the memory usage (not using the $temp variable or any variable to copy the reversed string to) and I failed.
This kept bugging me and since then I tried to solve this multiple times but I constantly failed.
My latest try looks like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . $s;
}
var_dump($s);
// outputs string(14) "gfedcbaabcdefg"
It's not a solution to chop off "abcdefg" after the loop because then I would still double the amount of memory used. I need to remove the last character in every iteration of the loop.
I tried to use mb_substr like this:
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i * 2} . mb_substr($s, $length - $i - 1, 1);
}
var_dump($s);
but it only gives me Uninitialized string offset errors.
This is where I'm stuck (again). I tried googling but all the solutions I found either echo the characters directly or use a temporary variable.
I also found the Question PHP String reversal without using extra memory but there's no answer that fits my needs.
That's an interesting one.
Here's something I just came up with:
$s = 'abcdefghijklm';
for($i=strlen($s)-1, $j=0; $j<$i; $i--, $j++) {
list($s[$j], $s[$i]) = array($s[$i], $s[$j]);
}
echo $s;
list() can be used to assign a list of variables in one operation. So what I am doing is simply swapping characters (starting with first and last, then second-first and second-last and so on, till it reaches the middle of the string)
Output is mlkjihgfedcba.
Not using any other variables than $s and the counters, so I hope that fits your criteria.
You can use the fact that in PHP a string can be thought of as an array of characters.
Then basically what you want to do is to replace each character $i on the left side of the middle of the string with the character $j on the right side of the middle with the same distance.
For example, in a string of seven characters the middle character is on position 3. The character on position 0 (distance 3) needs to be swapped with the character on position 6 (3 + 3), the character on position 1 (distance 2) needs to be swapped with the character on position 5 (3 + 2), etc.
This algorithm can be implemented as follows:
$s = 'abcdefg';
$length = strlen($s);
for ($i = 0, $j = $length-1; $i < ($length / 2); $i++, $j--) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
}
var_dump($s);
$string = 'abc';
$reverted = implode(array_reverse(str_split($string)));
You could use the XOR swap trick.
function rev($str) {
$len = strlen($str);
for($i = 0; $i < floor($len / 2); ++$i) {
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
$str[$len - $i - 1] = $str[$i] ^ $str[$len - $i - 1];
$str[$i] = $str[$i] ^ $str[$len - $i - 1];
}
return $str;
}
print rev("example");
Try this:
$s = 'abcdefg';
for ($i = strlen($s)-1; $i>=0; $i--) {
$s .= $s[$i];
$s[$i] = NULL;
}
var_dump(trim($s));
Here it is PHP7 version of this:
echo "\u{202E}abcdefg"; // outs: gfedcba
PHP strings are kinda-sorta mutable, but due to copy-on-write it's very difficult to modify them in-place without a copy being made. Some of the above solutions work, but only because they're stand-alone; some already fail because they define a function without a pass-by-reference argument. To get the code to actually operate in-place in a larger program, you'd need to pay careful attention to assignments, function arguments, and scopes.
Example:
$string1 = 'abc';
$string2 = $string1;
$string1[0] = 'b';
print("$string1, $string2");
> "abc, bbc"
I suppose that if between initializing the variable and modifying it you only ever used by-reference assignments (&=) and reference arguments (function rev(&$string)) (or assign the string to an object property initially, and then never assign it to any other variable), you might be able to change the original value of the string without making any copies. That's a bit ridiculous, however, and I'd assume that the interviewer who came up with that question didn't know about copy-on-write.
This isn't quite the same as immutability in other languages, by the way, because it applies to arrays too:
$a = [0, 1, 2];
$b = $a;
$b[0] = 1;
print(implode($a).implode($b));
> "012112"
To sum up, all types (except for objects as of PHP5) are assigned with copy-on-write unless you specifically use the &= operator. The assignment doesn't copy them, but unlike most other languages (C, Java, Python...) that either change the original value (arrays) or don't allow write access at all (strings), PHP will silently create a copy before making any changes.
Of course, if you switched to a language with more conventional pointers and also switched to byte arrays instead of strings, you could use XOR to swap each pair of characters in place:
for i = 0 ... string.length / 2:
string[i] ^= string[string.length-1-i]
string[string.length-1-i] ^= string[i]
string[i] ^= string[string.length-1-i]
Basically #EricBouwers answer, but you can remove the 2nd placeholder variable $j
function strrev2($str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
return $str;
}
Test for the output:
echo strrev2("Hi there!"); // "!ereht iH"
echo PHP_EOL;
echo strrev2("Hello World!"); // "!dlroW olleH"
This will go through the list and stop halfway, it swaps the leftmost and rightmost, and works it's way inward, and stops at the middle. If odd numbered, the pivot digit is never swapped with itself, and if even, it swaps the middle two and stops. The only extra memory used is $len for convenience and $tmp for swapping.
If you want a function that doesn't return a new copy of the string, but just edits the old one in place you can use the following:
function strrev3(&$str)
{
$len = strlen($str);
for($i=0;$i<$len/2;$i++)
{
$tmp = $str[$i];
$str[$i] = $str[$len-$i-1];
$str[$len-$i-1] = $tmp;
}
}
$x = "Test String";
echo $x; // "Test String"
strrev3($x);
echo PHP_EOL;
echo $x; // "gnirtS tseT"
Using &$str passes a direct pointer the the string for editing in place.
And for a simpler implementation like #treegardens, you can rewrite as:
$s = 'abcdefghijklm';
$len = strlen($s);
for($i=0; $i < $len/2; $i++) {
list($s[$i], $s[$len-$i-1]) = array($s[$len-$i-1], $s[$i]);
}
echo $s;
It has the similar logic, but I simplified the for-loop quite a bit.
Its Too Simple
//Reverse a String
$string = 'Basant Kumar';
$length = strlen($string);
for($i=$length-1;$i >=0;$i--){
echo $string[$i];
}
Here is my code to solve your problem
<?php
$s = 'abcdefg';
for ($i = 0, $length = mb_strlen($s); $i < $length; $i++) {
$s = $s{$i}.mb_substr($s,0,$i).mb_substr($s,$i+1);
}
var_dump($s);
?>
You could also use a recursion to reverse the string. Something like this for example:
function reverse($s) {
if(strlen($s) === 1) return $s;
return substr($s, strlen($s)-1) . reverse(substr($s , 0, strlen($s)-1));
}
What you do here is actually returning the last character of the string and then calling again the same function with the substring that contains the initial string without the last character. When you reach the point when your string is just one character then you end the recursion.
You can use this code to reverse a string without using the reserved function in php.
Code:
<?php
function str_rev($y)// function for reversing a string by passing parameters
{
for ($x = strlen($y)-1; $x>=0; $x--) {
$y .= $y[$x];
$y[$x] = NULL;
}
echo $y;
}
str_rev("I am a student");
?>
Output:
tneduts a ma I
In the above code, we have passed the value of the string as the parameter.We have performed the string reversal using for loop.
you could use substr with negative start.
Theory & Explanation
you can start with for loop with counter from 1 to length of string, and call substr inside iteration with counter * -1 (which will convert the counter into negative value) and length of 1.
So for the first time counter would be 1 and by multiplying with -1 will turn it to -1
Hence substr('abcdefg', -1, 1); will get you g
and next iteration substr('abcdefg', -2, 1); will get you f
and substr('abcdefg', -3, 1); will get you e
and so on ...
Code
$str = 'abcdefghijklmnopqrstuvwxyz';
for($i=1; $i <= strlen($str); $i++) {
echo substr($str, $i*-1, 1);
}
In Action: https://eval.in/583208
public function checkString($str){
if(!empty($str)){
$i = 0;
$str_reverse = '';
while(isset($str[$i])){
$strArr[] = $str[$i];
$i++;
}
for($j = count($strArr); $j>= 0; $j--){
if(isset($strArr[$j])){
$str_reverse .= $strArr[$j];
}
}
if($str == $str_reverse){
echo 'It is a correct string';
}else{
echo 'Invalid string';
}
}
else{
echo 'string not found.';
}
}
//Reverse String word by word
$str = "Reverse string word by word";
$i = 0;
while ($d = $str[$i]) {
if($d == " ") {
$out = " ".$temp.$out;
$temp = "";
}
else
$temp .= $d;
$i++;
}
echo $temp.$out;
The following solution is very simple, but it does the job:
$string = 'Andreas';
$reversedString = '';
for($i = mb_strlen($string) - 1; $i >= 0; $i--){
$reversedString .= $string[$i];
}
var_dump($reversedString) then results: string(7) "saerdnA"
<?php
$value = 'abcdefg';
$length_value = strlen($value);
for($i = $length_value-1; $i >=0 ;$i--){
echo $value[$i];
}
?>
you can try this..
$string = "NASEEM";
$total_word = strlen($string);
for($i=0; $i<=$total_word; $i++)
{
echo substr($string,$total_word-$i,1);
}
i have used some built in function but without str_rev function .
<?php
$text = "red";
$arr = str_split($text);
$rev_text = array_reverse($arr);
echo join(" ",$rev_text);
?>
Try This
<?php
$str="abcde";
for($i=strlen($str)-1;$i>=0;$i--){
echo $str[$i];
}
?>
output
edcba
This is my solution to solve this.
$in = 'This is a test text';
$out = '';
// find string length
$len = strlen($in);
// loop through it and print it reverse
for ( $i = $len - 1; $i >=0;$i-- )
{
$out = $out.$in[$i];
}
echo $out;
Reverse string using recursion function.
$reverseString = '';
function Reverse($str, $len)
{
if ($len == 0) {
return $GLOBALS['reverseString'];
} else {
$len--;
$GLOBALS['reverseString'] .= $str[$len];
return Reverse($str, $len);
}
}
$str = 'Demo text';
$len = strlen($str);
echo Reverse($str, $len)
Try this
$warn = 'this is a test';
$i=0;
while(#$warn[$i]){
$i++;}
while($i>0)
{
echo $warn[$i-1]; $i--;
}

Random number that is 15 characters long and positive

I am trying to make random numbers that are exactly 15 characters long and positive using php. I tried rand(100000000000000, 900000000000000) but it still generates negatives and numbers less than 15. Is there another function I am missing that can do this, or should I just use rand(0, 9) 15 times and concatenate the results?
$i = 0;
$tmp = mt_rand(1,9);
do {
$tmp .= mt_rand(0, 9);
} while(++$i < 14);
echo $tmp;
You are using a 32 bit platform. To handle these integers, you need a 64bits platform.
You can do the rand two times and save it as a string, like this:
$num1 = rand(100000,999999);
$num2 = rand(100000,999999);
$num3 = rand(100,999);
$endString = $num1.$num2.$num3;
PS. I like tiggers solution better than mine.
Keep in mind that this will return a string, not an actual integer value.
function randNum($length)
{
$str = mt_rand(1, 9); // first number (0 not allowed)
for ($i = 1; $i < $length; $i++)
$str .= mt_rand(0, 9);
return $str;
}
echo randNum(15);
Here you go.
function moreRand($len) {
$str = mt_rand(1,9);
for($i=0;$i<$len-1;$i++) {
$str .= mt_rand(0, 9);
}
return $str;
}
echo moreRand(15);
Edit: If you want to shave .00045s off your execution time,
function randNum() { return abs(rand(100000000000000, 900000000000000)); }

generating a random code in php?

i know this might seem silly, but i want to generate a random code of 8 characetrs, only numbers or letters using php. i needs this to generate a password for each user that signs up, thanks
I would rather use md5 to generate passwords
But you can use something like this if you want a custom:
function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
What about something like this, for ease:
$pass = substr(md5(uniqid(mt_rand(), true)) , 0, 8);
A good or efficient method for doing this is:
public function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrs092u3tuvwxyzaskdhfhf9882323ABCDEFGHIJKLMNksadf9044OPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
By changing $length variable you can generate alphanumeric code according to your need.
<?php
$uniqid = uniqid();
$rand_start = rand(1,5);
$rand_8_char = substr($uniqid,$rand_start,8);
?>
This work like charm and you can choose the type of characters that will be generated like:
"upper_case", "lower_case", "number", "special_character"
function create_random_code($length = 8, $in_params = [])
{
$in_params['upper_case'] = isset($in_params['upper_case']) ? $in_params['upper_case'] : true;
$in_params['lower_case'] = isset($in_params['lower_case']) ? $in_params['lower_case'] : true;
$in_params['number'] = isset($in_params['number']) ? $in_params['number'] : true;
$in_params['special_character'] = isset($in_params['special_character']) ? $in_params['special_character'] : false;
$chars = '';
if ($in_params['lower_case']) {
$chars .= "abcdefghijklmnopqrstuvwxyz";
}
if ($in_params['upper_case']) {
$chars .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
if ($in_params['number']) {
$chars .= "0123456789";
}
if ($in_params['special_character']) {
$chars .= "!##$%^&*()_-=+;:,.";
}
return substr(str_shuffle($chars), 0, $length);
}
To use it:
echo create_random_code(
6,
[
'upper_case' => true,
'lower_case' => true,
'number' => true,
'special_character' => false
]
);
Use base64_encode(), feed it some rand() numbers, and cut off the first 8 characters, which are definitely letters or numbers. That's not a totally random combination due to the input being just integers. But it's good enough for default user-passwords. (Else use rand() via chr() before encoding.)
PHP has a rand function (and also a mt_rand function that the docs claim is faster.)
So do something like this:
$i = 0;
$pwd = "";
while ( $i < 10) {
if (mt_rand() % 2 == 0) {
$pwd .= rand();
} else {
$pwd .= char(rand());
// http://php.net/manual/en/function.chr.php
}
$i += 1;
}
For your purposes, you can use the following to generate random codes:
bin2hex(random_bytes(10))
Note that here we use random_bytes, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_int was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), array_rand(), and shuffle(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
The code above generates a string of 20 hexadecimal characters (0 to 9, or A to F). If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question.
I also list other things to keep in mind when generating unique identifiers, especially random ones.

I was wondering how can I generate random numbers and letters together using PHP

how can I generate random numbers and letters mixed together.
Here is my php code.
$i=1;
while($i<=10000){
echo $i++;
}
Here is the function I use
function rand_str($n = 32, $str = "abcdefghijklmnopqrstuvwxyz0123456789")
{
$len = strlen($str);
$pin = "";
for($i = 0; $i < $n; $i++)
{
$rand = rand(0, $len - 1);
$letter = substr($str, $rand, 1);
$pin .= $letter;
}
return $pin;
}
PHP offers the function uniqid(). This function guarantees a unique string.
As such, the values from uniqid() are fairly predictable, and should not be used in encryption (PHPs rand(), by the way, is considered fairly unpredictable).
Running uniqid(), prefixed with rand() trough md5() give more unpredictable values:
$quite_random_token = md5(uniqid(rand(1,6)));
The other benefit of this, is that md5() assures hashes (strings) that are 32 characters/numbers long.
It's normally good to have some type of string / text class that allows you to do this in a reusable fashion, rather than just writing one off functions / writing the code inline.
<?php
class Text
{
/**
* Generate a random string
* #param string $type A type of pool, or a string of characters to use as the pool
* #param integer $length Length of string to return
* #return string
*/
public static function random($type = 'alnum', $length = 8)
{
$pools = array(
'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'hexdec' => '0123456789abcdef',
'numeric' => '0123456789',
'nozero' => '123456789',
'distinct' => '2345679ACDEFHJKLMNPRSTUVWXYZ'
);
// Use type as a pool if it isn't preconfigured
$pool = isset($pools[$type]) ? $pools[$type] : $type;
$pool = str_split($pool, 1);
$max = count($pool) - 1;
$str = '';
for ($i = 0; $i < $length; $i++)
{
$str .= $pool[mt_rand(0, $max)];
}
return $str;
}
}
here is an example usage:
http://codepad.org/xiu7rYQe
You need something this:
$chars = 'ABCDEFGHIJKLMNOPQRSTOUVWXYZ0123456789';
$i = 0;
do{
$i++;
$ret .= $ret.$chars[mt_rand(0,35)];
}while($i<$length+1);
YOu can print a random alpha numeric character like this:
print chr(rand(97, 122));
Check the ascii chars you want to return. 97 = a and 122 = z. (I think that's right)
Edit: That's almost right. You'll have to include 0-9 but that'e enough to get you started.
Here's mine.
<?php
function randomMixed($length) {
$output = '';
$rand = array_merge(range('a','z'), range('A','Z'), range('0','9'));
for($i = 0; $i < $length; $i++) {
$output .= $rand[array_rand($rand)];
}
return $output;
}
?>
As told by greg0ire, you can use uniqueid() function in following way to generate alphanumeric random number:
printf("uniqid(): %s\r\n", 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