Php learning notes: uses the gd library to generate images and implement Random verification codes,

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.