PHP simple custom method to generate random strings
/** * 生成随机字符串 * @param string $lenth 长度 * @return string 字符串 */ function get_randomstr($lenth = 6) { return get_random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'); } /** * 产生随机字符串 * * @param int $length 输出长度 * @param string $chars 可选的 ,默认为 0123456789 * @return string 字符串 */ function get_random($length, $chars = '0123456789') { $hash = ''; $max = strlen($chars) - 1; for($i = 0; $i < $length; $i++) { $hash .= $chars[mt_rand(0, $max)]; } return $hash; }
Usage:
echo get_randomstr(6); echo get_randomstr(7);
Output:
vS8wZK hQ17fEI
The above two results will be randomly generated, and the structure will be different every time it is run.
Analysis:
Pass in the number of generated strings through parameters to the method get_randomstr(); the get_randomstr() method then generates a random number through the get_random method and returns it to get_randomstr(). In fact, this process is through two I personally think it is more cumbersome to complete it with a custom method, although the idea is clear. In fact, the advantage of this method is that when we hard-code the get_random method in the public method, if we later find that some functions cannot be satisfied by get_random, we can extend it through the get_randomstr method.
So under normal circumstances, I recommend that you use the following method to generate random strings:
Several methods of generating PHP random numbers