Php learning notes: uses the gd library to generate images and implement Random verification codes,
Note: I have commented on some basic code. Here, you can set the number of digits of the verification code and the required strings. With my comments, you can easily understand them.
Basic Ideas:
1. use mt_rand () to randomly generate a number to determine the string to be obtained and splice the string (think the generated verification code is a bit crowded, you can splice a Space key in the middle of the string ), implement Random verification code;
Note: We recommend that you use mt_rand () instead of rand () for higher efficiency.
2. Use the gd library to generate images and write random strings to image output.
Effect:
A Random verification is generated for each refresh. Later I may add how to implement random code and click the image to update it again.
Code:
<? Php // create a canvas $ width = 120; // specify the width and height of the canvas $ height = 45; $ image = imagecreatetruecolor ($ width, $ height ); // create a true color image // Add some colors to be used $ white = imagecolorallocate ($ image, 0xf2, 0xec, 0xe0); $ orange = imagecolorallocate ($ image, 0xff, 0xa5, 0x4c); // fill in the canvas background color imagefill ($ image, 0, 0, $ white); // mt_rand obtain the random number mt_rand (min, max ); function str_rand () {$ str = "abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ"; $ rand = ""; for ($ I = 0; $ I <5; $ I +) {// obtain 5 random strings $ rand. = $ str [mt_rand (0, strlen ($ str)-1)]; // For example, if the random number is 30, return $ rand ;} $ verifyCode = str_rand (); // draw a string on the canvas imagestring ($ image, 10, 10, 10, "$ verifyCode", $ orange ); // notify the browser that the output is an image (png Type) header ('content-Type: image/png '); // output to the browser imagepng ($ image ); // release image resources