| PHP verification code implementation principle
Generate a random number or letter and save it to the session (used to verify the verification code). then plot the generated number or letter! And then present it to us.
Refresh verification code: use js to change the parameters of the verification code image so that the browser does not read the cached image to refresh the verification code! Sample code
- $ 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 (125,200), mt_rand (), mt_rand ));
- }
- For ($ I = 1; $ I <= mt_rand (); $ I ++) {imageline ($ image, mt_rand (), mt_rand ), mt_rand (100,150), mt_rand (), mt_rand ();} header ("content-type: image/png"); imagepng ($ image);?>
- Digit + letter verification code (different letters in different colors ):
- $ 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 (125,200), mt_rand (), mt_rand ));
- }
- For ($ I = 1; $ I <= mt_rand (1, 5); $ I ++ ){
- Imageline ($ image, mt_rand (100,150), mt_rand ));
- }
- Header ("content-type: image/png ");
- Imagepng ($ image );
From: php verification code implementation principle |