本文主要和大家分享PHP实现生成随机码,小伙伴让写一个生成5位随机码的函数,要求:可包含数字、字母大小写,代码尽量短。
解题思路
(1) . 第一思路
都是印象中匹配ASCII码进行随机读取的实现方法,此处可提供一个方法作为参考:
function get_rand_ascii($pw_length = 5){ $randpwd = ''; for ($i = 0; $i < $pw_length; $i++) { $randpwd .= chr(mt_rand(33, 99)); } return $randpwd; }
(2) . 第二思路
1.定义随机数组,内含能够使用的所有字符
function getRandomString($length=5) { //可任意添加需要的字符 $chars = array( "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ); $charsLen = count ( $chars ) - 1; shuffle ( $chars ); // 将数组打乱 $output = ""; for($i = 0; $i < $length; $i ++) { $output .= $chars [mt_rand ( 0, $charsLen )]; } return $output; }
提示:此类的代码,建议去除可能引起歧义的字符,如:1、I、l、0、o、O、9、q.
缺点:5个字符没有重复
2.比较上述 1 中的数组形式,设计字符串形式参考如下:
function get_pass( $length = 8 ) { // 密码字符集,可任意添加你需要的字符 $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; }
(3) . 第三思路
发现的新思路,可使用加密算法进行获取
public function getRand(){ $rand = rand(10000,100000); $str = substr(base64_encode($rand), 0, 5); return $str; }
提示:md5()函数只有数字和小写的字母
发现:base64_encode()可以满足要求
拓展延伸
针对于PHP设计,一般的随机码可用于验证码、分享码的生成,着重注意位数的限制,必要情况下,保证该随机码的唯一性.
password_hash 的使用(PHP>5.5)
可用于用户的密码加密存储,不过有一点需注意:如果数据库迁移,对于java或.net语言将难以适用.
$password = 'password1232456';//前端 获取的原始密码 //数据库存放的 使用BCRYPT算法加密的密码 //此处仅为测试,实际应用时应从数据表中查询获得 //$db_pass = '$2y$10$2vJJC.rb/swAUnTfc9B94.l/ix75kiZHvOZFpu0Dd8uzp07YWlj4q'; $db_pass = password_hash($password, PASSWORD_BCRYPT); if (password_verify($password , $db_pass)){ echo "密码匹配"; }else{ echo "密码错误"; }
相关推荐:
The above is the detailed content of PHP implements generating random codes. For more information, please follow other related articles on the PHP Chinese website!

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.


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

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
