Thinkphpp5.1 verification code function implementation example code



ThinkPHP5.1It has appeared for a long time and has been contacted recently. The following describes the use of commonly used third-party captcha functions.

Environmental Science

  • Framework version: thinkphp5.1.2
  • The operating environment is as follows

♜ function development

1) . introduction of third party extension packages

To develop TP5,ComposerThe use of will become an important skill towindowsFor example, enter the command:

composer require topthink/think-captcha

To complete the above operation, it will appear in the following directorycaptchaExpansion pack for


2) . front end settings

In front of the page need to show the location of the verification code, supplement{:captcha_img()}The personal code is as follows:

  < label > captcha
  < input type = "text" name = "verifycode" placeholder = "please enter verification code" > "

3) Code optimization of captcha extension package

If the above operation is followed, the displayed captcha image can not be refreshed by clicking, you can design the refresh function according to the requirements; or, the following code optimization is recommended:

function captcha_img($id = "")
 $js_src = "this.src='".captcha_src()."'";
 return '<img src="' . captcha_ SRC ($ID) '"title =" click to update the verification code "ALT =" click to update the verification code "ο nclick =". $JS_ src.'" />';
 //return '![](' . captcha_src($id) . ')';

open..\vendor\topthink\think-captcha\src\helper.phpFile, replace abovecaptcha_img()Method code

At this time, the captcha image can be clickReal time refreshFunction

[Note: February 26, 2020]

Recently, it has been found that the code above is copied directly on CSDN. After “onclick” paste, it is not normal code. Pay attention to the letter “O”. It is suggested that if there is a problem, you can type it by hand!

4) . background code verification

According to the front end requestverifyCodeData, callinghelper.phpMediumcaptcha_check()Methods.

   $data = input('post.');
   if(!captcha_check($data['verifyCode'])) {
    //Verification failed
    $this - > error ('incorrect verification code ');

♞ tips

Official documents——[thinkphpp5.1 captcha guide]

  • Suggested reading..\vendor\topthink\think-captcha\src\helper.phpDocuments, andCaptcha.php, you can customize the style
  • If the front end{:captcha_img()}If there is a value ID, then the backgroundcaptcha_check()The verification also needs the corresponding ID parameter distinction.
  • Validation results, commonly usedajaxRequest to meet the user’s smooth experience

This article on the implementation of the thinkphpp5.1 captcha function of the article introduced here, more about the content of thinkphpp5.1 captcha, please search the previous articles of developeppaer or continue to browse the related articles below, I hope you can support developeppaer more in the future!