Create a random string

From FacileWiki

Contributed in the forum by conlippert

Here's my handy function as promised (researched for best practices): getrandomstring(x); give it a length, 9 for example and get a totally random string of letters and numbers such as: '9NoktBriOb' or 'SFB8eISkVI' great for unique record id's.

Example:

$rec_id = getrandomstring(9);

function getrandomstring($length) 
{
    global $template;
    settype($template, "string");

    $template = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    settype($length, "integer");
    settype($rndstring, "string");
    settype($a, "integer");
    settype($b, "integer");
       
    for ($a = 0; $a <= $length; $a++) {
        $b = rand(0, strlen($template) - 1);
        $rndstring .= $template[$b];
    }
       
    return $rndstring;
}
| Terms of Use | Privacy | Sitemap |
Editing tools
Personal tools