PHP verification code implementation principle
Generate random numbers or letters and save them in the session (used when verifying the verification code), and then draw the generated numbers or letters! Then present them in front of our eyes
Refresh the verification code: Use js to change the parameters of the verification code image so that the browser does not read the cached image, thereby achieving the effect of refreshing the verification code!
Code example
- $str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
-
- $image=imagecreate(50,25);
- imagecolorallocate($image,mt_rand(0,125),mt_rand(0,125),mt_rand( 0,125));
- $ color = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
- for($i=1;$i<=4;$i++) {
- $date=$str[mt_rand( 0,strlen($str)-1)];
- $code.=$date;
- }
- session_start();
- $_SESSION['code'] = $code;
- imagestring($image,4,8,4 ,$code,$color);
- for($i=1;$i<=30;$i++) {
- imagesetpixel($image,mt_rand(0,50),mt_rand(0,25),mt_rand(125,200) );
- }
- for($i=1;$i<=mt_rand(1,5);$i++) { imageline($image,mt_rand(0,50),mt_rand(0,25),mt_rand(0, 50),mt_rand(0,25),mt_rand(100,150)); } header("content-type:image/png"); imagepng($image); ?>
- Number + letter verification code (each letter has a different color ):
-
- $str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
- $image=imagecreate(50,25);
- imagecolorallocate($image,mt_rand(0,125),mt_rand( 0,125),mt_rand(0,125));
- $color[0] = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
- $color[1] = imagecolorallocate($image,mt_rand (200,255),mt_rand(200,255),mt_rand(200,255));
- $color[2] = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
- $color[3] = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
- for($i=0;$i<4;$i++) {
- $date=$str[mt_rand(0,strlen ($str)-1)];
- $code.=$date;
- imagestring($image,5,6+$i*10,4,$code[$i],$color[$i]);
- }
- session_start();
- $_SESSION['code'] = $code;
- for($i=1;$i<=30;$i++) {
- imagesetpixel($image,mt_rand(0,50),mt_rand (0,25),mt_rand(125,200));
- }
- for($i=1;$i<=mt_rand(1,5);$i++) {
- imageline($image,mt_rand(0,50), mt_rand(0,25),mt_rand(0,50),mt_rand(0,25),mt_rand(100,150));
- }
- header("content-type:image/png");
- imagepng($image);
Copy code
From: PHP verification code implementation principle
|