这里有新鲜出炉的 PHP 设计模式,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
本篇文章主要介绍了 PHP 中快速生成随机密码的几种方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
思路是这样的,密码通常是英文字母和数字的混合编排,我们可以借助随机函数 rand 函数随机的选择一个长字符串的一部分。
- function random_code($length = 8, $chars = null) {
- if (empty($chars)) {
- $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- }
- $count = strlen($chars) - 1;
- $code = '';
- while (strlen($code) < $length) {
- $code. = substr($chars, rand(0, $count), 1);
- }
- return $code;
- }
- echo random_code; //A1zYbN5X
我们使用 rand 函数的目的是为了产生随机的字符串,但是如果有一个函数可以做到的话,我们就没有必要使用 rand 函数了。
- function random_char($length = 8, $chars = null) {
- if (empty($chars)) {
- $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- }
- $chars = str_shuffle($chars);
- $num = $length < strlen($chars) - 1 ? $length: str_len($chars) - 1;
- return substr($chars, 0, $num);
- }
可以看到不使用 rand 函数,而是使用 str_shuffle 函数,好处是大大减少了代码量。
更近一部的,我们的函数不仅可以生成随机的密码,还可以生成短信验证码,以及高强度的服务器登录密码。
- function random_code_type($length = 8,$type = 'alpha-number'){
- $code_arr = array(
- 'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
- 'number'=> '0123456789',
- 'sign' => '#$%@*-_',
- );
- $type_arr = explode('-',$type);
- foreach($type_arr as $t){
- if( ! array_key_exists($t,$code_arr)){
- trigger_error("Can not generate type ($t) code");
- }
- }
- $chars = '';
- foreach($type_arr as $t){
- $chars .= $code_arr[$t];
- }
- $chars = str_shuffle($chars);
- $number = $length > strlen($chars) - 1 ? strlen($chars) - 1:$length;
- return substr($chars,0,$number);
- }
- echo random_code_type(8,"alpha-number-sign");#kXM*mC$S
来源: http://www.phperz.com/article/17/0814/340167.html