使用PHP生成随机数可以应用在许多地方,比如可以设计程序的随机密码、模拟掷骰子游戏的应用程序、石头剪子布游戏应用程序等等
有时候我们需要在应用程序中使用随机生成用户名和密码,这样可以大大提高应用程序的安全,在PHP中生成随机用户名和密码可以使用 mt_rand 函数或者是 rand 函数, rand 函数在验证码中的应用多一些,而生成长字符的随机码一般都需要 mt_rand 函数。
下面是PHP生成随机数的两个函数方法:
代码如下:
//自动为用户随机生成用户名(长度6-13) function create_password($pw_length = 4){ $randpwd = ''; for ($i = 0; $i < $pw_length; $i++){ $randpwd .= chr(mt_rand(33, 126)); } return $randpwd; } function generate_username( $length = 6 ) { // 密码字符集,可任意添加你需要的字符 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|'; $password = ''; for ( $i = 0; $i < $length; $i++ ) { // 这里提供两种字符获取方式 // 第一种是使用substr 截取$chars中的任意一位字符; // 第二种是取字符数组$chars 的任意元素 // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); $password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; } return $password; } // 调用该函数 $userId = 'user'.generate_username(6); $pwd = create_password(9);
【相关教程推荐】
1. php编程从入门到精通全套视频教程
2. php从入门到精通
3. bootstrap教程
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article
How to fix KB5055612 fails to install in Windows 10?
4 weeks agoByDDD
Roblox: Grow A Garden - Complete Mutation Guide
3 weeks agoByDDD
Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
