RSS

Generate a random password in PHP

24 Jul

Here you go to generate a random password in php, that is a random string with a specifc length from a specific group of characters.

First decide the characters that can be included, here we assume only alpha-numeric,

then,

$chars = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;

And we assume the default length of password as 20,

$length = 20

Here goes the function,
function generateRandPassword($length = 20) {
                       $chars = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
                       $randPass = ”;
                        for ($i = 0; $i < $length; $i++) {
                               $randPass .= $characters[rand(0, strlen($chars) – 1)];
                        }
                        return $randPass;
                  }

 
2 Comments

Posted by on July 24, 2012 in PHP

 

Tags: , , , ,

2 responses to “Generate a random password in PHP

  1. Christian Dover

    July 25, 2012 at 2:19 pm

    That’s not random. rand() and mt_rand() are not suitable for security purposes (generating passwords, session keys, etc) because they are PRNGs, which have predictable output. When doing anything with security, you need a CSPRNG. Reading ‘/dev/urandom’ will work on some systems and mcrypt_create_iv() will work when ‘mcrypt’ is available. If you want something more portable, I recommend using:

    http://barebonescms.com/documentation/csprng/

    Which will work across platforms and a variety of web hosts. Of course, generating a password implies that you are developing a login system. Making a login system is good as an exercise, but you should use a prepackaged system like:

    http://barebonescms.com/documentation/sso/

    When deploying a login system to a production environment. I’ve used that particular project a number of times already.

     
  2. Creators

    August 10, 2012 at 1:34 pm

    Ya but this is for a simple logic, not for complex secures systems

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: