ThinkPHP5驗證碼的實現


關於如何創建tp5的工程,本文就不在贅述,不懂的可以google查找相關內容,本文直接是在已經創建好的tp5環境進行實現的

如果已經安裝 think-captcha擴展包,則跳過第一個步驟。

1.使用composer安裝 think-captcha 擴展包

關於如何安裝composer,可以訪問網址進行正確安裝。

使用cmd,切換到ThinkPHP的應用根目錄下,執行:

composer require topthink/think-captcha

出現以下界面則表明安裝成功:

說明:

如果出現以下錯誤:

表示本地下載ThinkPHP版本不支持默認下載的think-captcha版本,需要自己指定版本

composer require topthink/think-captcha=1.*

2.前端代碼,文件名index.test.html,最為簡單的方式,沒有使用到css

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Test/title>
 6     <script type="text/javascript"src="http://code.jquery.com/jquery-latest.js"></script>
 7 </head>
 8 <body>
 9 <div class="codeImg">
10     <img src="{:url('index/index/newCode',['t'=>time()])}" title="點擊更換" alt="captcha" class="captcha_img" id="captcha_img" onclick="changeCode()"/>
11 </div>
12 <input type="text" id="code">
13 <input type="button" id="submit" onclick="submitCode()" value="驗證">
14 <script>
15     function submitCode() {
16         // 獲取用戶輸入的值
17         code = $("#code").val();
18         // 使用ajax請求后台
19         $.ajax({
20             type : "POST",
21             dataType:"json",
22             data:{
23                 'code':code
24             },
25             url :"/index/index/verfycode",
26             success : function(rs) {
27                 // 簡單輸出驗證成功還是失敗
28                 alert(rs);
29             }
30         });
31     }
32     // 用戶點擊驗證碼圖片,改變驗證碼
33     function changeCode(){
34         $("#captcha_img").attr("src",'{:url("index/index/newCode")}?t='+parseInt(40*Math.random()));
35     }
36 </script>
37 </body>
38 </html>

3.接下來是實現后端PHP代碼

 1 <?php
 2 namespace app\index\controller;
 3 use think\captcha\Captcha;
 4 use think\Controller;
 5 class Index extends Controller
 6 {
 7     public function test(){
 8         // 自動定位到 index.test.html 文件
 9         // 具體config.php配置文件這里不細說
10         this->fetch();
11     }
12     public function verfycode(){
13         // 獲取ajax請求的值
14         $code = input("code");
15         // 進行驗證碼的驗證
16         if (captcha_check($code)){
17             return '驗證成功';
18         } else {
19             return '驗證失敗';
20         }
21     }
22     public function newCode(){
23         // 配置驗證碼的顯示方式和內容
24         $config =    [
25             // 驗證碼位數
26             'length'      =>    4,
27             // 驗證碼過期時間
28             'expire'      =>    300,
29             // 是否添加雜點
30             'useNoise' => true,
31             // 是否畫混淆曲線
32             'useCurve' => false,
33             // 是否使用背景圖片
34             'useImgBg' => false,
35             // 使用字體
36             'fontttf' => '3.ttf'
37         ];
38         $captcha = new Captcha($config);
39         return $captcha->entry();
40     }
41 }

詳細闡述驗證碼的配置:

4.運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM