前段顯示代碼:
<?php
session_start();
include_once 'conn/conn.php';
for($i=0; $i<4; $i++){
$num .= dechex(rand(0,15));
}
?>
//驗證碼顯示代碼
<span>驗證碼:<input id="lgchk" type="text" style=" width: 75px; height: 16px; border: 1px #999999 solid;" /></span><br />
<span>
<img id='chkid' src="login/valcode.php?num=<?php echo $num; ?>" width="55" height="18" />
<a id="changea" style="cursor:hand;">看不清</a>
</span><br />
// 登錄部分顯示代碼
<div style=" background-color:#597ecf; height: 25px; line-height: 25px;">
<input id="chknm" name="chknm" type="hidden" value="<?php echo $num; ?>" />
<a id="lgbtn" style=" color:#f0f0f0;">登錄</a>
<a id="reg" style=" color:#f0f0f0;">註冊</a>
<a id="foundbtn" style=" color:#f0f0f0;">找回密碼</a>
</div>
第一次進入此頁面時,請求後端的頁面,如上代碼先生成一個隨機字符串,然後使用剛纔的隨機字符串生成請求後端的url,訪問valcode.php腳本,由後端腳本生成顯示的驗證碼圖片,最終生成要顯示的頁面,顯示於前端。
js代碼:
$('changea').onclick = function(){
num = '';
for(i=0; i<4; i++){
tmp = Math.ceil((Math.random() * 15));
switch(tmp){
case(10):
num += 'a';
break;
case(11):
num += 'b';
break;
case(12):
num += 'c';
break;
case(13):
num += 'd';
break;
case(14):
num += 'e';
break;
case(15):
num += 'f';
break;
default:
num += tmp;
break;
}
}
$('chkid').src='login/valcode.php?num='+num;
$('chknm').value = num;
}
當單擊看不清按鈕時,觸發js代碼中的按鍵事件函數,生成隨機字符串,再修改驗證碼圖片的URL,然後瀏覽器在請求後端的圖片資源,最後顯示在前端的就是新的驗證碼圖片。
後端代碼:
<?php
header("content-type:image/png");
$num = $_GET['num'];
$imagewidth = 60;
$imageheight = 18;
srand(microtime() * 100000);
$numimage = imagecreate($imagewidth, $imageheight);
imagecolorallocate($numimage, 183, 180, 83);
for($i = 0; $i < strlen($num); $i ++){
$font = mt_rand(3, 5);
$x = mt_rand(1, 8) + $imagewidth * $i / 4;
$y = mt_rand(1, $imageheight / 4);
$color = imagecolorallocate($numimage, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200));
imagestring($numimage, $font, $x, $y, $num[$i], $color);
}
imagepng($numimage);
imagedestroy($numimage);
?>