Generate a random string in PHP

 

I created this class primarily to generate random salts for passwords, but it can be used quite easily to create random strings of any length that you specify.

<?php
    /**
     * clsSalt
     *
     * @package 
     * @author Satal Keto
     * @copyright 2008
     * @version v1.00.002
     * @access public
     */
    class clsSalt
    {
        /**
         * clsSalt::generateSalt()
         * A static function which generates salt's   
         *
         * @param Integer $saltLen
         * @return String, The salt which was requested
         */
        public static function generateSalt($saltLen = 32)
        {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`¬¦!"£$%^&*()-_=+[{}]#~;:'@,<.>/?\";
            srand((double)microtime()*1000000);
            $i = 0;
            $salt = '' ;
            //Because $i is 0 we use < rather than <= as otherwise we would get $saltLen + 1
            while ($i < $saltLen)
            {
                $num = rand() % strlen($chars);
                $char = substr($chars, $num, 1);
                $salt = $salt . $char;
                $i++;
            }
            return $salt;
        }
    }
?>