IT.COM

[TUTORIAL]Generating Random string

Spaceship Spaceship
Watch
Impact
0
Just simple code to generate random strings:

You can change the chars in $chars :)

PHP:
<?
function RandomString($length)
{
	$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
	srand((double)microtime() * 1000000);
	$str = "";
	$i = 0;
	
	    while ($i < $length) {
			$num = rand() % 33;
			$tmp = substr($chars, $num, 1);
			$str = $str . $tmp;
			$i++;
		}
	return $str;
}

$string = RandomString(5);

echo "$string";
?>
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Great function. The one I usually use for PHP is:

PHP:
<?php
function random_id(){
	$charset='0123456789abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVQXYZ';
	$max=strlen($charset)-1;
	$id='';
	$len=32;
	while($len--)
		$id.=$charset[mt_rand(0,$max)];
	return $id;
}
?>

It appears to be slightly faster. And for JavaScript:

Code:
function random_id(){
	var
		charset='0123456789abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVQXYZ',
		max=charset.length,
		id='',
		len=32,
		ptr;
	while(len--)
		id+=charset.substring(ptr=Math.floor(Math.random()*max),ptr+1);
	return id
};
 
0
•••
0
•••
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back