PHP Learning notes: Using the GD library to generate images and implement random verification codes

Source: Internet
Author: User

Description: I have commented on some basic code, the number of verification codes implemented here, the strings that need to be used can be set again. With my comments, you should be able to read it easily.

Basic ideas:

1. Use Mt_rand () randomly generated numbers to determine the string to be obtained, concatenation of the string (feel that the generated verification code is a bit too crowded, you can re-string in the middle of the space bar), the implementation of random verification code;

Note: It is recommended that you use Mt_rand () instead of Rand (), which is more efficient

2. Use the GD library to generate images and write random strings to the image output.

Effect:

Each refresh, generates a random verification, later I may also add how to implement random code click on the image to update 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 of the colors that will be used$white= Imagecolorallocate ($image, 0xf2, 0xec, 0xe0);$orange= Imagecolorallocate ($image, 0xFF, 0xa5, 0x4c);//fill the canvas background with colorImagefill ($image, 0, 0,$white);//Mt_rand Gets the random number Mt_rand (min, max);    functionStr_rand () {$str= "ABCDEFGHIJKMNPQRSTUVWXYZ0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ"; $rand="";  for($i= 0;$i<5;$i++){//get 5 random strings            $rand.=$str[Mt_rand(0,strlen($str)-1)];//For example: 30 random number: $str [+]        }        return $rand; }$verifyCode=Str_rand ();//draw a string of strings on the canvasImagestring ($image, 10, 10, 10, "$verifyCode",$orange);//notifies the browser that the output is an image (PNG type)Header(' Content-type:image/png ');//Output to BrowserImagepng ($image);//Releasing image Resources

PHP Learning notes: Using the GD library to generate images and implement random verification codes

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.