Welcome, guest | Sign In | My Account | Store | Cart

This function will generate a salt for use with passwords ranging using characters in range a to z, A to Z, 0 to 9 and !@#$%&?. The characters are sorted in a random value and can appear more than one time in the string. This way, this function is more powerful than the *shuffle() function. This means that the salt could also be longer than the character list.

PHP, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/**
 * This function generates a password salt as a string of x (default = 15) characters
 * in the a-zA-Z0-9!@#$%&*? range.
 * @param $max integer The number of characters in the string
 * @return string
 * @author AfroSoft <info@afrosoft.tk>
 */
function generateSalt($max = 15) {
        $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*?";
        $i = 0;
        $salt = "";
        while ($i < $max) {
            $salt .= $characterList{mt_rand(0, (strlen($characterList) - 1))};
            $i++;
        }
        return $salt;
}

?>

This code snippet is provided to you courtesy of AfroSoft: http://afrosoft.tk/.

Part of SMUtility

6 comments

roger matelot 12 years, 9 months ago  # | flag

mt_rand(0,strlen($characterList)) will occasionally return index that is one letter out of $characterList.

Xavier L. (author) 12 years, 9 months ago  # | flag

Thanks, I forgot about that, modified it.

TurboHz 12 years, 7 months ago  # | flag

The loop executes $max+1 times, because it goes from [0..$max]. It should be: while ($i < $max), which is [0..$max)

Xavier L. (author) 12 years, 5 months ago  # | flag

Thanks, I updated it.

Alvin Mites 11 years, 9 months ago  # | flag

I think line 14 should be

 while ($i <= $max) {
Xavier L. (author) 11 years, 9 months ago  # | flag

Indeed. Fixed it!

Created by Xavier L. on Tue, 1 Sep 2009 (MIT)
PHP recipes (51)
Xavier L.'s recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks