PHP+jq實現驗證碼

-前端頁面

<div class="demo">
<h3>2、數字驗證碼</h3>
<p>驗證碼:<input type="text" class="input" id="code_num" maxlength="4" /> <img src="../addons/lb_vote/code_char.php" id="getcode_num" title="看不清,點擊換一張" align="absmiddle" /></p>
<p><input type="button" class="btn" id="chk_num" value="提交" /></p>
</div>

-jq

<!--驗證碼-->
<script type="text/javascript" src="../addons/lb_vote/Public/js/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
 $("#getcode_num").click(function() { //數字驗證
 $(this).attr("src", 'code_char.php?' + Math.random());
 });
 $("#chk_num").click(function() {
 var code_num = $("#code_num").val();
 $.post("../addons/lb_vote/chk_code.php?act=num", {
  code: code_num,
 },
 function(msg) {
  if (msg == 1) {
  alert("驗證碼正確!");
  } else {
  alert("驗證碼錯誤!");
  }
 });
 });
});

</script>

-code_char.php

<?php
session_start();
getCode(4,60,20);
function getCode($num,$w,$h) {
 $code = "";
 for ($i = 0; $i < $num; $i++) {
 $code .= rand(0, 9);
 }
 //4位驗證碼也可以用rand(1000,9999)直接生成
 //將生成的驗證碼寫入session,備驗證時用 
 $_SESSION["helloweba_num"] = $code;
 //創建圖片,定義顏色值
 header("Content-type: image/PNG");
 $im = imagecreate($w, $h);
 $black = imagecolorallocate($im, 0, 0, 255);
 $gray = imagecolorallocate($im, 255, 64, 0);
 $bgcolor = imagecolorallocate($im, 172, 83, 83);
 //填充背景
 imagefill($im, 0, 0, $gray);
 //畫邊框
 imagerectangle($im, 0, 0, $w-1, $h-1, $black);
 //隨機繪製兩條虛線,起干擾作用
 $style = array ($black,$black,$black,$black,$black,
 $gray,$gray,$gray,$gray,$gray
 );
 imagesetstyle($im, $style);
 $y1 = rand(0, $h);
 $y2 = rand(0, $h);
 $y3 = rand(0, $h);
 $y4 = rand(0, $h);
 imageline($im, 0, $y1, $w, $y3, IMG_COLOR_STYLED);
 imageline($im, 0, $y2, $w, $y4, IMG_COLOR_STYLED);
 //在畫布上隨機生成大量黑點,起干擾作用;
 for ($i = 0; $i < 80; $i++) {
 imagesetpixel($im, rand(0, $w), rand(0, $h), $black);
 }
 //將數字隨機顯示在畫布上,字符的水平間距和位置都按一定波動範圍隨機生成
 $strx = rand(3, 8);
 for ($i = 0; $i < $num; $i++) {
 $strpos = rand(1, 6);
 imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $black);
 $strx += rand(8, 12);
 }
 imagepng($im);//輸出圖片
 imagedestroy($im);//釋放圖片所佔內存
}
?>

-chk_code.php

<?php
  session_start();
   $sessioncode=$_SESSION["helloweba_num"];
   $code=$_POST['code'];
   if($sessioncode==$code){
       $msg=1;
        echo json_encode($msg);

   }else{
    $msg=2;
     echo json_encode($msg);

   }
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章