PHP生成随机字符串

生成随机字符串,一般是大小写英文字母与数字混合或者单纯数字排列组合,通常用于数据库保存账户密码的时候,密码加密前拼接“加噪”干扰字符串,然后进行加密。保证密码的安全性。


话不多说,直接贴方法代码:

方法一:基础方法

/**
 * 生成随机字符串
 * @param  integer $length  随机字符串长度
 * @param  bool    $numeric 是否生成数字串
 * @return string          返回的字符串
 */
function getRand($length=6,$numeric = false){
	
	$str="0 1 2 3 4 5 6 7 8 9 q w e r t y u i o p a s d f g h j k l z x c v b n m Q W E R T Y U I O P A S D F G H J K L Z X C V B N M";
	if($numeric){
		$str="0 1 2 3 4 5 6 7 8 9";
	}
	
	$arr=explode(' ', $str);
	shuffle($arr);
	$str=implode('', $arr);
	return substr($str,0,$length);
}

方法二:高级方法

/**
 * 生成随机字符串
 * @param  integer $length  随机字符串长度
 * @param  bool    $numeric 是否生成数字串
 * @return string          返回的字符串
 */
function random($length, $numeric = FALSE) {
	$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
	if ($numeric) {
		$hash = '';
	} else {
		$hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
		$length--;
	}
	$max = strlen($seed) - 1;
	for ($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

两种方法,殊途同归,都可以完成任务! 微笑

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值