Random Code

I am using random codes a lot. I use them for generating API keys, random passwords, email verification links and more. I have a single function written in PHP that I am using over and over again. As it saves me loads of work I thought some of you might be able to use it as well.

Selec All Code:
1
2
3
4
5
6
7
8
9
10
11
12
function randomCode($length = 10) {
    $possible = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
 
    $code= '' ;
 
    for ($i=0; $i < $length; $i++) {
        $pos= rand(0,strlen($possible)-1);
        $code.= substr($possible , $pos, 1);
    } 
 
    return $code;
}

It is really easy to use.

If you want to generate a code with the length of 10 simply do it this way.

Selec All Code:
1
$code = randomCode();

If you want it any shorter or longer than 10 do it this way

Selec All Code:
1
$code = randomCode(30);

Any feedback is welcome

This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">