Generating Random String using php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Generating Random String using php

Post by Saman » Fri Sep 03, 2010 3:57 am

There are two good methods to generate random strngs with php.

Method 1:

Code: Select all

function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters)-1)];
    }

    return $string;
} 

Method 2:

Code: Select all

function getUniqueCode($length = "")
{    
    $code = md5(uniqid(rand(), true));
    if ($length != "") return substr($code, 0, $length);
    else return $code;
}
 
Post Reply

Return to “PHP & MySQL”