2014年10月24日 01:37:39

PHP生成随机密码

作者: 
本文提供一个基于Web和CLI两种运行方式的PHP生成随机密码示例代码,用户可以很方便得实现批量动态密码的生成,还能通过定制字符串,生成符合自己要求的随机密码,灵活方便。演示:PHP生成动态密码(演示)
 <?php
/**
 *
 * @author Zjmainstay
 * @website http://zjmainstay.cn
 * @copyright GPL
 * @version 1.0
 * @year 2014
 *
 */

//CLI Usage: php createPassword.php length=32\&type=all\&splitChar=_\&splitLength=4\&times=5

//动态关闭错误提示
ini_set('display_errors','off');
error_reporting(0);

if(isset($_GET['source'])) {
    highlight_file(__FILE__);
    exit;
}

//默认长度和类型
$length         = 32;
$type           = 'number-lower-upper';
$customType     = '';
$splitChar      = '';
$splitLength    = 4;
$times          = 1;
$isCli          = (PHP_SAPI=='cli') ? true : false;

if($isCli) {
    if(!empty($argv[1])) parse_str($argv[1], $_POST);
    else $_POST = array(
        'length'        => $length,
        'type'          => $type,
        'customType'    => $customType,
        'splitChar'     => $splitChar,
        'splitLength'   => $splitLength,
        'times'         => $times,
    );
}

if(!empty($_POST)) {
    /**
     *  获取随机密码函数
     *  @param string $type 密码字符串类型
     *  @param string $customStr 自定义密码组成字符
     *  @param int    $length 密码长度
     *  @param string $splitChar 分隔符,默认不分隔
     *  @param int    $splitLength 密码字符分隔长度 比如:密码为abc-def-ghi时$splitLength = 3
     *
     */
    function getPassword($type = 'number-lower-upper', $customStr = '', $length = 32, $splitChar = '', $splitLength = 4) {
        $strArr         = array(
            'number'    => '0123456789',
            'lower'     => 'abcdefghijklmnopqrstuvwxyz',
            'upper'     => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'special'   => '~!@#$%^&*()_+{}|[]\-=:<>?/',
        );
        
        if($type == 'all') {        //全部
            $str = implode('', $strArr);
        } else if($type == 'custom') {        //自定义类型
            if(empty($customStr)) {    //未填写自定义类型,则默认为数字+大小写字母
                $type    = 'number-lower-upper';
            } else {
                $str     = $customStr;
            }
        }
        
        //custom 没带自定义类型 或 其他类型
        if(empty($str)) {
            $typeParts  = explode('-', $type);
            $str        = '';
            foreach($typeParts as $part) {
                $str   .= $strArr[$part];
            }
        }
        
        $maxLength         = 32;    //最大长度
        $length            = empty($length) ? $maxLength : min((int)$length, $maxLength);
        if(empty($length)) {
            $length = $maxLength;
        }
        
        // 大数据下面str_shuffle会导致随机种子耗尽而导致结果循环(错误做法)
        // $passwordStr    = '';
        // do {
            // $randStr        = str_shuffle($str);
            // $passwordStr   .= substr($randStr, 0, 1);        //每次取一个字符
            // $passwordLength = strlen($passwordStr);
        // } while($passwordLength < $length);
        
        //纠正
        $passwordStr    = '';
        $strMaxIndex    = strlen($str) - 1;
        do {
            $randIndex      = mt_rand(0, $strMaxIndex);
            $passwordStr   .= $str[$randIndex];        //每次取一个字符
            $passwordLength = strlen($passwordStr);
        } while($passwordLength < $length);
        
        //需要分隔
        if($splitChar != '') {
            $passwordStr = implode($splitChar, str_split($passwordStr, $splitLength));
        }
        
        return $passwordStr;
    }
    
    $length         = empty($_POST['length'])       ? $length       : max(1, (int)$_POST['length']);
    $type           = empty($_POST['type'])         ? $type         : $_POST['type'];
    $customType     = empty($_POST['customType'])   ? $customType   : $_POST['customType'];
    $splitChar      = empty($_POST['splitChar'])    ? $splitChar    : $_POST['splitChar'];
    $splitLength    = empty($_POST['splitLength'])  ? $splitLength  : max(1, (int)$_POST['splitLength']);
    $times          = empty($_POST['times'])        ? $times        : min(100, max(1, (int)$_POST['times']));  //这里加了最大密码个数限制,可自行修改
    
    $passwordArr    = array();
    for($i = 0; $i < $times; $i++) {
        $passwordArr[] = getPassword($type, $customType, $length, $splitChar, $splitLength);
    }
    
    $password = implode("\n", $passwordArr);
    
    if($isCli) {
        echo $password;
        exit;
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>密码生成器</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="zh-CN" />
    <script type="text/javascript" src="http://www.zjmainstay.cn/jquerylib/jquery-1.8.2.min.js"></script>
</head>
<body>
<style type="text/css">
* {
    margin: 5px;
}
</style>
<form action="<?php echo $_SERVER['SCRIPT_NAME']?>" method="POST">
    <div>
    <label>长度:</label>
    <input type="text" name="length" value="<?php echo $length ?>" style="width: 100px;" placeholder="长度为0-32"/>
    </div>
    <div>
        <label>类型:</label>
        <select name="type" style="width: 150px;" id="type">
            <option value="number">纯数字</option>
            <option value="lower">小写字母</option>
            <option value="upper">大写字母</option>
            <option value="lower-upper">大小写字母</option>
            <option value="number-lower">数字+小写字母</option>
            <option value="number-upper">数字+大写字母</option>
            <option value="number-lower-upper">数字+大小写字母</option>
            <option value="special">特殊字符</option>
            <option value="number-special">数字+特殊字符</option>
            <option value="lower-special">小写字母+特殊字符</option>
            <option value="upper-special">大写字母+特殊字符</option>
            <option value="all">全部</option>
            <option value="custom">自定义</option>        
        </select>
        <input name="customType" type="text" style="display:none;" size="50" value="<?php echo $customType ?>"/>
    </div>
    <div>
        <label>密码分隔符(不填写则不分隔)</label>
        <input name="splitChar" type="text" value="<?php echo $splitChar ?>"/>
    </div>
    <div>
        <label>密码分隔长度</label>
        <input name="splitLength" type="text" value="<?php echo $splitLength ?>"/>
    </div>
    <div>
        <label>密码个数</label>
        <input name="times" type="text" value="<?php echo $times ?>"/>
    </div>
    <div>
    <input type="submit" value="生成"/>
    
    <?php if(!empty($password)) { ?>
    <div>
    <textarea id="password" readOnly="true" rows="10" cols="50"><?php echo $password ?></textarea><span class="tips"></span>
    </div>
    <?php } ?>
    </div>
</form>
<script type="text/javascript">
$(document).ready(function(){
    //初始化默认选择数字+大小写字母
    $("#type").get(0).selectedIndex = $("#type option").index($("#type option[value=<?php echo $type ?>]"));
    if($("#type").val() == 'custom') {
        $("input[name=customType]").show();
    }
    
    $("#type").change(function() {
        if($(this).val() == 'custom') {
            $("input[name=customType]").show();
        } else {
            $("input[name=customType]").hide();
        }
    });
    $("#password").click(function() {
        $(this).select();
        $(".tips").html("请使用 Ctrl + C 复制");
    });
});
</script>
</body>
</html> 

文件源码:PHP生成动态密码(源码)- Zjmainstay学习笔记



未经同意禁止转载!
转载请附带本文原文地址:PHP生成随机密码,首发自 Zjmainstay学习笔记
阅读( 4447 )
看完顺手点个赞呗:
(3 votes)

1.PHP cURL群:PHP cURL高级技术
2.正则表达式群:专精正则表达式
3. QQ联系(加请说明):QQ联系博主(951086941)
4. 邮箱:zjmainstay@163.com
5. 打赏博主:

网站总访问量: