Category Archives: PHP-How to generate random string

Random text(string) generation using PHP

First i would like to introduce two string function:

1 .Chr() function

The chr() function returns a character from the specified ASCII value.

syntax: chr(ascii)

How to use the chr() function:

<?php
echo chr(52).”<br />”;
echo chr(052).”<br />”;
echo chr(0x52).”<br />”;
?>

The output of the code above will be:

4
*
R

2 . rand() function

The rand() function generates a random integer.

If this function is called without parameters, it returns a random integer between 0 and RAND_MAX.

If you want a random number between 10 and 100 (inclusive), use rand (10,100).

Syntax

rand(min,max)

Example

<?php
echo(rand(10,100))
?>

Output:

67(or the number between 10 and 100)

ok lets move to the real tutorial. This tutorial will teach you how to generate the random string.

Coding:

<?

$lengthofstring = 10;
while($i < $lengthofstring ) {
$x=1;
$y=3;
$part = rand($x,$y); //returns either 1 or 2 or 3
if($part==1){$a=48;$b=57;}  // Numbers
if($part==2){$a=65;$b=90;}  // UpperCase
if($part==3){$a=97;$b=122;} // LowerCase
$code_part=chr(rand($a,$b));  // returns the character for the randomly generated character
$i++;
$newstring = $newstring.$code_part;
}
echo $newstring;
?>

Try this out…..