Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random string using PHP?

Tags:

string

php

random

I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:

Original string, 9 chars

$string = 'abcdefghi'; 

Example random string limiting to 6 chars

$string = 'ibfeca'; 

UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.

UPDATE: The function should generate any amount of chars as required.

Please comment the parts if you reply.

like image 439
Keith Donegan Avatar asked May 12 '09 17:05

Keith Donegan


People also ask

What function is used to create a random key?

Generates a pseudorandom (rather than a truly random) series of bytes to use as an encryption key, and returns the key as a RAW value.

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

php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) != 1) { foreach ($check as $val) { if ($val == $page_no) { $page_no = mt_rand(1,10); continue; } } return $page_no; } else { return $page_no; } } ?>

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 random string of characters in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


1 Answers

If you want to allow repetitive occurences of characters, you can use this function:

function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {     $str = '';     $count = strlen($charset);     while ($length--) {         $str .= $charset[mt_rand(0, $count-1)];     }     return $str; } 

The basic algorithm is to generate <length> times a random number between 0 and <number of characters> − 1 we use as index to pick a character from our set and concatenate those characters. The 0 and <number of characters> − 1 bounds represent the bounds of the $charset string as the first character is addressed with $charset[0] and the last with $charset[count($charset) - 1].

like image 151
Gumbo Avatar answered Sep 26 '22 21:09

Gumbo