PHP implementation of "Post-god beast" Verification code

Source: Internet
Author: User
Tags asin transparent image

The earliest to see "Stick God Beast" Verification code is posted in Baidu Bar, it is the main prevention of digging graves, released the Ultimate God Beast Verification code

For example:

Address: http://tieba.baidu.com/p/3320323440

This type of verification code can be implemented with PHP + JavaScript.

Using the jquery version: jquery 1.9.1

Framework uses thinkphp 3.2.3, custom verification code class based on TP code class

Eventually:

Custom Verification Code classpath:/application/home/common/verivypostbar.class.php

Controller:/application/home/controller/postbarcontroller.class.php

Views:/applicable/home/view/postbarverify/index.html

Custom Verification Code Class/application/home/common/verivypostbar.class.php

<?phpnamespace home\common;use Think\verify;class Verifypostbar extends Verify {private $_image = NULL;     Verification code Picture Instance Private $_color = NULL; CAPTCHA Font Color public Function entryprocess ($id = ") {//Picture width (px) $this->imagew | | $this->imagew = $this->leng    th* $this->fontsize*1.5 + $this->length* $this->fontsize/2; Picture height (px) $this->imageh | |    $this->imageh = $this->fontsize * 2.5; Create a transparent image $this->imagew x $this->imageh $this->_image = Imagecreatetruecolor ($this->imagew, $this->i     Mageh);    Imagesavealpha ($this->_image, true);    $trans _colour = Imagecolorallocatealpha ($this->_image, 0, 0, 0, 127);        Imagefill ($this->_image, 0, 0, $trans _colour);    CAPTCHA font random color $this->_color = imagecolorallocate ($this->_image, Mt_rand (1,150), Mt_rand (1,150), Mt_rand (1,150)); The captcha uses a random font $ttfPath = $_server[' Document_root '). ' /thinkphp/library/think/verify/'. ($this->usezh? ' Zhttfs ': ' TTFs '). ‘/‘;   if (Empty ($this->fontttf)) {$dir = Dir ($ttfPath);        $ttfs = Array ();                while (false!== ($file = $dir->read ())) {if ($file [0]! = '. ' && substr ($file,-4) = = '. Ttf ') {            $ttfs [] = $file;        }} $dir->close ();    $this->fontttf = $ttfs [Array_rand ($TTFS)]; } $this->fontttf = $ttfPath.        $this->fontttf;    if ($this->useimgbg) {$this->_background ();    } if ($this->usenoise) {//Plot dot//$this->_writenoise ();    } if ($this->usecurve) {//Draw interference line $this->_writecurve (); }//Draw verification Code $code = Array (); Verification code $codeNX = 0; Verification code Nth character left margin if ($this->usezh) {//Chinese captcha for ($i = 0; $i < $this->length; $i + +) {$code [$i]            = Iconv_substr ($this->zhset, $i, 1, ' utf-8 '); Imagettftext ($this->_image, $this->fontsize, Mt_rand ( -40, +), $this->fontsize* ($i + 1) *1.5, $this- FontSize + Mt_rand (Ten), $this->_color, $this->fontttf, $code [$i]); }//Alternate Captcha area (9 kanji) $len _pre_row = $this->area_length/$this->rows;          Number of words per line for ($r = 0; $r < $this->rows; $r + +) {$flag = 1;          $start = $r * $len _pre_row;          $end = $r * $len _pre_row + $len _pre_row-1;          $code _ = Array ();            for ($i = $start; $i < $end + 1; $i + +) {$code _[$i] = iconv_substr ($this->code_area, $i, 1, ' utf-8 ');  @param image//@param size//@param angle//@param x//@param Y//@param color//@param fontfile Imagettftext ($this->_image, $this->fontsize, Mt_rand ( -20), $this->fontsize*2 * $flag, $this->fontsize + $r +, $this->_color, $this->fontttf, $            code_[$i]); $flag + = 2; Control the x-coordinate of the CAPTCHA alternate character}}}//Save verification Code $key = $this->authcode ($this->sekey);    $code = $this->authcode (strtoupper (Implode (", $code)));    $secode = Array (); $secode [' verify_code '] = $code;  Save the check code to the session $secode [' verify_time '] = now_time;           Verification code creation time session ($key. $id, $secode);    Header (' Cache-control:private, max-age=0, No-store, No-cache, Must-revalidate ');    Header (' cache-control:post-check=0, pre-check=0 ', false);    Header (' Pragma:no-cache ');    Header ("Content-type:image/png");    Save image to Hard disk imagepng ($this->_image, ' public/home/images/verifyimage.png ');    Output image//Imagepng ($this->_image);    ReadFile (' public/home/images/verifyimage.png ');  Imagedestroy ($this->_image);}      /** * Draw the dots * to write letters or numbers of different colors on the picture */Private Function _writenoise () {$codeSet = ' 2345678abcdefhijkmnpqrstuvwxyz '; for ($i = 0; $i < $i + +) {//DOT color $noiseColor = imagecolorallocate ($this->_image, Mt_rand (150          , 225), Mt_rand (150,225), Mt_rand (150,225)); for ($j = 0; $j < 5; $j + +) {              Plot clutter Point imagestring ($this->_image, 5, Mt_rand ( -10, $this->imagew), Mt_rand ( -10, $this-&gt          ; imageh), $codeSet [Mt_rand (0,)], $noiseColor); }}}/** * draw a random sine function curve consisting of two lines as the interfering line (you can change to a more handsome curve function) * * High school math formula I forgot Nirvana, write it out * sine type function analytic: Y=asin (ωx+φ +b * The effect of each constant value on the function image: * A: Determines the peak (i.e. the multiple of the longitudinal stretch compression) * B: Indicates the position of the waveform on the Y axis or the longitudinal moving distance (upper plus minus) *φ: determines the waveform and x-axis position relationship or horizontal        Move distance (left plus right minus) *ω: Decision period (min positive period t=2π/∣ω∣) * */Private Function _writecurve () {$px = $py = 0;                  The front part of the curve $A = Mt_rand (1, $this-&GT;IMAGEVERIFYH/2);   Amplitude $b = Mt_rand (-$this-&GT;IMAGEVERIFYH/4, $this-&GT;IMAGEVERIFYH/4);   Y-axis direction offset $f = Mt_rand (-$this-&GT;IMAGIMAGEVERIFYHEH/4, $this-&GT;IMAGEVERIFYH/4);  X-axis direction Offset $T = Mt_rand ($this->imageverifyh, $this->imagew*2);                        Cycle $w = (M_PI)/$T;  $px 1 = 0;  Curve horizontal start position $px 2 = Mt_rand ($this->imagew/2, $this->imagew * 0.8); Curve Horizontal End bitPlace for ($px = $px 1; $px <= $px 2; $px = $px + 1) {if ($w!=0) {$py = $A * Sin ($w * $px + $f) + $b + $this-  >imageVerifyH/2;            y = Asin (ωx+φ) + b $i = (int) ($this-&GT;FONTSIZE/5);  while ($i > 0) {imagesetpixel ($this->_image, $px + $i, $py + $i, $this->_color);            This (while) loop is much better than Imagettftext and imagestring to draw (without this while loop) at one time with the font size $i-;    }}}}/* Cryptographic Verification Code */Private Function Authcode ($str) {$key = substr (MD5 ($this->sekey), 5, 8);    $STR = substr (MD5 ($STR), 8, 10);  return MD5 ($key. $str); /** * Draw Background image * Note: If the captcha output picture is larger, it will occupy more system resources */Private Function _background () {$path = DirName (__file__). '      /verify/bgs/';      $dir = Dir ($path);      $BGS = Array ();              while (false!== ($file = $dir->read ())) {if ($file [0]! = '. ' && substr ($file,-4) = = '. jpg ') { $BGS [] = $path.          $file;      }} $dir->close (); $gb = $bgs [Array_rand ($BGS)];      List ($width, $height) = @getimagesize ($GB);      Resample $bgImage = @imagecreatefromjpeg ($GB);      @imagecopyresampled ($this->_image, $bgImage, 0, 0, 0, 0, $this->imagew, $this->imageh, $width, $height);  @imagedestroy ($bgImage); }   }

  

Controller/application/home/controller/postbarcontroller.class.php

<?phpnamespace home\controller;use think\controller;use Home\common\verifypostbar;class PostBarVerifyController Extends Controller {//Interface Public Function index () {header (' content-type:text/html;charset=utf-8 '); $this->display () ;}    Verify Public Function check_verify ($code) {$verify = new Verifypostbar ();    if (! $verify->check ($code)) {return 400;    } else {return 200;  }}//prepare the Captcha character public Function Prepare_code () {///verification Code Length $length = 4;  Verification code Selection Length $selects = 12; Similar Chinese characters for a group, from 6 groups of 36 Chinese characters to extract 4 groups of 12 Chinese characters to make up the verification code picture Group $zhSet = Array (' Already ', ' self ', ' B ', ' ", ' nine ', ' Go '), array (' Tian ', ' by ', ' a ', ' shen ', ' white ' ' Day '), array (' Fish ', ' fishing ', ' Yu ', ' Yu ', ' Yu ', ' Yue ', array (' Please ', ' Qing ', ' love ', ' green ', ' clear ', ' dragonflies '), Array (' Treasure ', ' Jade ', ' den ', ' must ', ' empty ', ' control '), AR  Ray (' son ', ' zi ', ' seed ', ' cumin ', ' squeak ', ' capital '));  $tmp = Array ();  $count = count ($zhSet); $tmp = $this->rand (0, $count-1, 4);  Randomly generate 4 non-repeating numbers (4 groups are selected in 0-5 groups) as subscript $chars = Array (); foreach ($tmp as $key + $val) {$chars [] = $this->choose ($zhSet, $val, 3);//3 numbers per group}//select from each set of one-dimensional arrays a verification code of length 4, foreach ($chars as $key + $val) {$k = Mt_rand (0, Count ($val)-1); $code [] = $val [$k];  Captcha unset ($chars [$key] [$k]);  }//dump ($code);//Dump ($chars);d ie;  Merges the array into a one-dimensional array $characters = array ();  foreach ($chars as $key = + $val) {foreach ($val as $k + = $v) {$characters [] = $v;    }}//Alternate Verification Code area array $code _area_array = Array_merge ($code, $characters);  Shuffle ($code _area_array);  Alternate Captcha string $code _area = Implode (", $code _area_array);  $code = Implode (' ', $code);  $codes [' code_area '] = $code _area;  $codes [' code_area_array '] = $code _area_array;  $codes [' code '] = $code;  $codes [' characters '] = $characters;  $codes [' length '] = $length;  $_session[' code_area_array '] = $code _area_array;  return $codes;} Displays the Captcha public function verify () {$codes = $this->prepare_code (); $conf = Array (' Usezh ' = = True, ' zhset ' = = $cod es[' code ', ' code_area ' = $codes [' Code_area '], ' length ' = = $codes [' length '],//CAPTCHA length (number of Chinese characters) ' rows ' + 3,// Alternative area 3 Lines ' Area_lengTh ' = Mb_strlen ($codes [' Code_area '], ' utf-8 '),//alternate area kanji number ' fontSize ' =>20, ' Imagew ' =>320, ' Imageh ' =>600, '  Imageverifyh ' + 45,//4 Word Verification Code area height); $verify = new Verifypostbar ($conf); $verify->entryprocess (); }//From a series of consecutive numbers to select the number of distinct//@param $start The starting value of the number//@param $end number of the end value//@param $count The number of the selected public function rand ($sta  RT, $end, $count) {$tmp = range ($start, $end);  $tmp = Array_rand ($tmp, $count);  return $tmp; }//From each group of Chinese characters (a group of 6) Select N (4)//@param $array two-dimensional array//@param $key array $array subscript//@param $n Select several public function choose (  $array, $key, $n) {$arr = $array [$key];  $count = count ($arr);  $tmp _key = $this->rand (0, $count-1, $n);  $chars = Array ();  foreach ($tmp _key as $val) {$chars [] = $arr [$val];  } return $chars;  }//Record the number of clicks, if the number reaches 4 times to make a judgment, the verification code input is correct public function Count_ckick () {session_start ();  Array of coordinates $codes = $_session[' Code_area_array '); $xy = Array (' line1_y ' =>array (' x1 ' =>0, ' x2 ' =>1, ' x3 ' =>2, ' x4 ' =>3,), ' line2_y ' =>array (' x1 ' =>4, ' x2 ' =>5, ' x3 ' =>6, ' x4 ' =>7,) ' Line3_y ' =>array (' x1 ' =>8, ' x2 ' =>9, '  X3 ' =>10, ' x4 ' =>11,));  if (! isset ($_post[' clear]) | | $_post[' Clear ']! = 1) {$_session[' count '] = $count = $_post[' count '];  if ($count > 4) {$_session[' count '] = 4;  } else {//record the selected captcha text $x = $_post[' x '];  $y = $_post[' y ']; foreach ($xy as $key = + $val) {foreach ($val as $k + $v) {if ($y = = $key) {if ($x = = $k) {$code _key = $codes [$v  ];  }}}}} if (! isset ($_session[' Input_code ')) {$_session[' input_code '] = $code _key;  } else {$_session[' input_code ']. = $code _key;  } $return = ' clicked '. $_session[' count ']. ', the selected kanji is: '. $code _key. ' Enter the verification code: '. $_session[' Input_code '];  if ($count = = 4) {$code = $this->check_verify ($_session[' Input_code '));  if ($code = =) {$return. = ' input correct ';  } else {$return. = ' input error ';  }}echo $return;  } else {//clears the number of clicks $_session[' count '] = 0;  unset ($_session[' Input_code '); Echo ' successfully cleared the clickNumber of clicks, $_session[' count ', ' Times ';  }}//Gets the number of clicks recorded in the session public function Record_click () {session_start ();  if (! isset ($_session[' count ')) {$_session[' count '] = 0;  } echo $_session[' count '];  }//Modify the number of Click Records Public Function Update_click () {session_start ();  if (! isset ($_session[' count ')) {$_session[' count '] = 0;  } else {$newcount = $_session[' count '] + $_post[' times ');  if ($newcount < 0) {$_session[' count '] = 0;  unset ($_seiion[' Input_code ');  } else {$_session[' count '] = $newcount;  $_session[' Input_code ' = mb_substr ($_session[' Input_code '], 0,-1, ' utf-8 ');  }} The echo ' hits are: '. $_session[' count ']. ' The captcha is: '. $_session[' Input_code ']; } }

  

View/applicable/home/view/postbarverify/index.html

<! DOCTYPE html>

  

Demonstrate

Initial state:

Enter the verification code:

Input complete, return result, error when:

Input complete, return result, correct when:

To delete a verification code:

Refresh Verification Code:

Reference:

Summary of methods for generating non-repeating random numbers in PHP

CSS transparent opacity and IE versions Transparency Filter filter the most accurate usage

PHP implementation of "Post-god beast" Verification code

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.