PHP uses session and gd library to generate and verify simple verification codes. sessiongd

Source: Internet
Author: User

PHP uses session and gd library to generate and verify simple verification codes. sessiongd

The verification code is used to prevent website contamination and increase the server load caused by machine irrigation. Currently, verification codes are available for large and small websites. Today, I implemented a simple verification code class. Simply put, it is because there are no interference arcs and so on, but the text is rotated. Of course, it is not easy to see it at a glance because of the font. At the same time, in order to avoid confusion between uppercase and lowercase letters and numbers, we also removed the letters and numbers that look very similar.
Class:

<? Php/*** simple verification code generation class */class Captcha {private $ width; // Verification Code width private $ height; // Verification Code height private $ countOfChars; // number of characters // private $ distrubLines; // Number of interfering lines private $ chars; // randomly generated string public function _ construct ($ width = 100, $ height = 30, $ countOfChars = 4, $ distrubLines = 2) {// initialization parameter $ this-> width = $ width; $ this-> height = $ height; $ this-> countOfChars = $ countOfChars; session_start ();}/*** execute all the actions, generate the verification code, and directly output */public function Execute () {$ imageHandle = $ this-> createImage (); $ this-> createChars (); $ this-> drawChars ($ imageHandle ); $ this-> outImage ($ imageHandle);}/*** create a canvas and randomly fill in the color * @ return canvas handle */public function createImage () {$ imageHandle = imagecreate ($ this-> width, $ this-> height); // random background color $ randColor = imagecolorallocate ($ imageHandle, 50, mt_rand (0, 50), mt_rand (0, 50); imagefill ($ imageHandle, 0, 0, $ randColor); return $ ImageHandle;}/*** generate random character */private function createChars () {// candidate character $ str = 'abcdefghjklmnpqrstuvwxzabcdefghijkmnpqtuvwx21_89 '; $ chars = ''; for ($ I = 0; $ I <$ this-> countOfChars; $ I ++) {$ chars. = $ str [mt_rand (0, strlen ($ str)-1)] ;}$ this-> chars = $ chars; // save in SESSION $ _ SESSION ['captcha '] = strtolower ($ chars );} /*** write characters into the image * @ param type $ imageHandle image handle */private function drawChars ($ imageHandle) {if ($ this-> cha Rs! = Null) {$ font = '/home/WWW/YuWeiLiShuFT. ttf'; for ($ I = 0; $ I <strlen ($ this-> chars); $ I ++) {$ color = imagecolorallocate ($ imageHandle, mt_rand (50,200), mt_rand (100,255), 255); imagefttext ($ imageHandle, 30, 30, $ I * 20 + 10, 25, $ color, $ font, $ this-> chars [$ I]) ;}}/ *** output image * @ param type $ imageHandle image handle */private function outImage ($ imageHandle) {imagepng ($ imageHandle); imagedestroy ($ imageHandle );} /*** determine whether the verification code entered by the user is correct * @ param type $ usrInput whether the user's input * @ return boolean verification code matches */public static function isRight ($ usrInput) {if (isset ($ _ SESSION ['captcha ']) {if (strtolower ($ usrInput) ==$ _ SESSION ['captcha']) {$ _ SESSION ['captcha '] = null; return true;} else {$ _ SESSION ['captcha'] = null; return false ;}}}}

Set verification to static method, because the verification code has been saved to the session after the verification code is generated. The static method is called directly during verification without instantiating this class.

The font above can be set at will.

The following code returns an image that is dynamically generated after the Captcha class is instantiated. (OutCaptcha. php)

<?phprequire('Captcha.php');$code= new Captcha();header('Content-Type:image/png');$code->execute();

Header ('content-Type: image/png ');

The purpose of this sentence is to tell the browser that the output is a png Image, rather than html code. After receiving the message, the browser parses the following output into an image.

Write an HTML static page (testcaptcha.html) to create a form.

<! DOCTYPE html> 

This is not enough. Do you see the address of the Form submission? That is used to verify whether the verification code is entered correctly:

Session_start (); $ inputCaptcha = trim ($ _ POST ['input _ captcha ']); require ('captcha. php '); if (Captcha: isRight ($ inputCaptcha) {echo 'verification code right';} else {echo 'verification Code incorrect or expired';} session_destroy ();

Import the Captcha class and call its static method to verify your input. Finally, the entire session is destroyed.

Finally, let's look at the effect.

That's great. It's successful. Try again by mistake, move back, and refresh (if the browser is not refreshed, the image of the verification code in the cache will be directly called. At this time, our verification code has not yet been generated! So no matter what the problem is ).

Of course, you can click another verification code, which uses ajax technology.

The above PHP class method that uses session and gd library to generate and verify simple verification codes is all the content that I have shared with you. I hope to give you a reference, we also hope that you can support the customer's home.

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.