Generate 5 character random 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.

Tim Cooper

153k37 gold badges319 silver badges272 bronze badges

asked Mar 25, 2011 at 22:26

3

$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"]

answered Mar 25, 2011 at 22:28

Brad ChristieBrad Christie

98.7k16 gold badges149 silver badges198 bronze badges

6

If for loops are on short supply, here's what I like to use:

$s = substr[str_shuffle[str_repeat["0123456789abcdefghijklmnopqrstuvwxyz", 5]], 0, 5];

answered Mar 26, 2011 at 0:34

MatthewMatthew

46.8k11 gold badges85 silver badges97 bronze badges

7

A speedy way is to use the most volatile characters of the uniqid function.

For example:

$rand = substr[uniqid['', true], -5];

answered Mar 25, 2011 at 22:40

John ParkerJohn Parker

53.6k11 gold badges128 silver badges128 bronze badges

2

You can try it simply like this:

$length = 5;

$randomletter = substr[str_shuffle["abcdefghijklmnopqrstuvwxyz"], 0, $length];

more details: //forum.arnlweb.com/viewtopic.php?f=7&t=25

clami219

2,8881 gold badge29 silver badges43 bronze badges

answered Jun 29, 2016 at 22:25

0

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]:


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:
//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[]:


answered Mar 26, 2011 at 0:32

ArcArc

10.9k4 gold badges49 silver badges72 bronze badges

3

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

answered Mar 25, 2011 at 22:36

1

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

answered Sep 12, 2016 at 16:08

1

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= 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];

answered Dec 24, 2015 at 13:10

SpookySpooky

1,16014 silver badges17 bronze badges

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

Tom

4,2266 gold badges33 silver badges49 bronze badges

answered Mar 24, 2017 at 15:23

1

I`ve aways use this:


When you call it, sets the lenght of string.


You can also change the possible characters in the string $a.

answered May 11, 2016 at 4:03

LipESprYLipESprY

2812 silver badges8 bronze badges

1

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{|}~

answered Jan 31 at 16:02

CodeBrauerCodeBrauer

2,3551 gold badge23 silver badges48 bronze badges

Not the answer you're looking for? Browse other questions tagged php random or ask your own question.

How do I generate a random character in PHP?

PHP rand function generates a random string..
$size = strlen[ $chars ];.
for[ $i = 0; $i < $length; $i++ ] {.
$str= $chars[ rand[ 0, $size - 1 ] ];.
echo $str;.

How can I generate 5 random numbers in PHP?

The rand[] function generates a random integer. Example tip: If you want a random integer between 10 and 100 [inclusive], use rand [10,100]. Tip: As of PHP 7.1, the rand[] function has been an alias of the mt_rand[] function.

What is Mt_rand function in PHP?

The mt_rand[] function is a drop-in replacement for the older rand[]. It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand[] provides.

How do you generate a non repeating random number in PHP?

php session_start[]; if [! isset[$_SESSION['numbers']]] { $_SESSION['numbers']="*"; //---create the session variable } function get_number[] { $i = 0; do { $num=rand[1,20]; //---generate a random number if [! strstr[$_SESSION['numbers'],"*".

Chủ Đề