Thursday, November 7, 2013

Generate random Passwords in PHP

Hiiii, when we make some user registration system in our project or code then we always want to keep the user details like password etc very secure which is not easy to detect and which is random for each and every user. You can try to make random password by applying some logic but here in this demo I'll be providing you with a very simple and short code to generate a random password.
This random passwords are also necessary when you have to send a confirmation mail to users with some password different from their identities. Users have to change their random passwords to their own password on first login.
Don't interpret the meaning of these random password with passwords generated by some encryption techniques like md5 hash, etc. The random passwords here are generated in php by making a string with some logic by adding a digit to that password string.
In this technique which I'll be showing here, you can generate the password of your desired length.




CODE BEGINS :

<?php
function get_random_string($valid_chars,$length)
{
    // start with an empty random string
    $random_string = "";

    // count the number of chars in the valid chars string so we know how many choices we have
    $num_valid_chars = strlen($valid_chars);

    // repeat the steps until we've created a string of the right length
    for ($i = 0; $i < $length; $i++)
    {
        // pick a random number from 1 up to the number of valid chars
        $random_pick = mt_rand(1, $num_valid_chars);

        // take the random character out of the string of valid chars
        // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
        $random_char = $valid_chars[$random_pick-1];

        // add the randomly-chosen char onto the end of our string so far
        $random_string .= $random_char;
    }

    // return our finished random string
    return $random_string;
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$length=10;
$pass=get_random_string($chars,$length);
echo $pass;
?>


Hope you like this post……..Please Comment…………!!!!!!!!!


Tags:

0 Responses to “Generate random Passwords in PHP”

Post a Comment

© 2013 MyCodeStock. All rights reserved.
Designed by SpicyTricks