Home > Backend Development > PHP Tutorial > PHP生成随机密码函数

PHP生成随机密码函数

WBOY
Release: 2016-06-20 13:03:46
Original
1079 people have browsed it

PHP生成随机密码函数,当需要生成随机数或者生成随机密码的时候可以用到,有需要的朋友可以参考一下,具体函数代码如下:

//PHP生成随机数密码函数(默认六位)

function randStr($len=6,$format='ALL'){<br />	switch($format){<br />		case 'ALL':<br />			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';<br />		break;<br />		case 'CHAR':<br />			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';<br />		break;<br />		case 'NUMBER':<br />			$chars='0123456789';<br />		break;<br />		default :<br />			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; <br />		break;<br />	}<br />	mt_srand((double)microtime()*1000000*getmypid()); <br />	$password='';<br />	while(strlen($password)<$len){<br />		$password.=substr($chars,(mt_rand()%strlen($chars)),1);<br />	}<br />	return $password;<br /><p>}
Copy after login

php生成随机数的几种方法,总结如下:

第一种方法,非常简单,直接使用系统自带的函数:

srand((double)microtime()*1000000); <br />//随机产生0-99之间的整数<br />$randval=rand(0,99999999);<br />echo $randval,'<br />';
Copy after login


/* 类似输出:32659912 */

第二种方法,稍微复杂一点,不只是生成只有数字的随机字符串,更包括了各种特殊字符:

function randomkeys($length){<br />	$output='';<br />	for($a=0;$a<$length; $a++){<br />		$output.=chr(mt_rand(33, 126));    <br />	}<br />	return $output;<br />}<br />echo randomkeys(20);
Copy after login


/* 类似输出:EGztLufY\Eq/br{y!;>P */


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template