Home >php教程 >php手册 >PHP生成随机字符串的几种方法

PHP生成随机字符串的几种方法

WBOY
WBOYOriginal
2016-06-06 20:12:491181browse

#方法1 function make_password( $length = '8'){ $range = array_merge( range('a', 'z') , range('A', 'Z') , range('0','9')); shuffle($range); $range = array_slice($range,0, $length); $password = implode('' , $range); return $password;} 评价:

#方法1

function make_password( $length = '8'){
    $range = array_merge( range('a', 'z') , range('A', 'Z') , range('0','9'));
    shuffle($range);
    $range = array_slice($range,0, $length);
    $password = implode('' , $range);
    return $password;
}

评价:看起来比较舒服,可以根据需求 自定义字符集,缺点是效率低。

#方法2

function generate_password( $length = 8 ) {
    // 密码字符集,可任意添加你需要的字符
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}~`+=,.;:/?|';
    $password = '';
    $chars_max_index = strlen($chars)-1;
    for ( $i = 0; $i 
<h4>评价:高效,因为仅使用了一个<code>mt_rand()</code>函数;可以根据需求 自定义字符集,不过看起来有点乱。</h4>
<h3><strong>#方法3</strong></h3>
<pre class="brush:php;toolbar:false">function create_password($pw_length = 8)
{
    $randpwd = '';
    for ($i = 0; $i 
<h4>评价:非常高效,利用ASCII码和<code>mt_rand()</code>,<code>chr()</code>完成随机字符串;可以根据需求 自定义字符集。</h4>
<h3><strong>#方法4</strong></h3>
<pre class="brush:php;toolbar:false">function get_password( $length = 8 )
{
    $str = substr(md5(time()), 0, 6);
    return $str;
}

评价:尼玛。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn