首先使用Composer安裝think-captcha擴展包:
composer require topthink/think-captcha
控制器引入
use think\captcha\facade\Captcha;
開啟session
代碼如下:
1 <?php 2 namespace app\controller; 3 4 use app\BaseController; 5 use think\captcha\facade\Captcha; 6 7 class Food extends BaseController { 8 9 // 模版 10 public function show() { 11 return view(); 12 } 13 14 // 生成常規驗證碼 15 public function verify() { 16 return Captcha::create(); 17 } 18 19 // 驗證驗證碼是否正確 20 public function test() { 21 $code = input('code'); 22 // 檢測輸入的驗證碼是否正確,$code為用戶輸入的驗證碼字符串 23 if (!captcha_check($code)) { 24 echo "驗證失敗"; 25 } else { 26 echo "成功"; 27 } 28 } 29 }
視圖:show.html
<!DOCTYPE html> <html> <head> <title></title> <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script> </head> <style type="text/css"> input { height: 30px; line-height: 30px; } </style> <body> <form action="test" method="post"> <table> <tr> <td>用戶名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密 碼</td> <td><input type="text" name="pwd"></td> </tr> <tr> <td>驗證碼</td> <td><input type="text" name="code"> <img id="codePic" height="30px" src="{:url('food/verify')}" onclick="flush()"> </td> </tr> <tr> <td> <button>注冊</button> </td> </tr> </table> </form> </body> </html> <script type="text/javascript"> function flush() { $("#codePic").attr("src","{:url('food/verify')}?flag="+Math.random()); } </script>
效果圖: