以前輸出驗證碼的時候用過一個方法,在前臺用JS生成驗證碼字符串,再傳遞到后臺用PHP輸出驗證碼圖像。這樣在驗證時就不需要使用$_SESSION傳遞驗證碼的值,直接用JS比較生成的字符串和輸入的字符串是否相等即可。
本文以實例演示5種驗證碼,并介紹生成驗證碼的函數。PHP生成驗證碼的原理:通過GD庫,生成一張帶驗證碼的圖片,并將驗證碼保存在Session中。
1、HTML
5中驗證碼HTML代碼如下:
<div class="demo"> <h3>1、數字驗證碼</h3> <p>驗證碼:<input type="text" class="input" id="code_num" name="code_num" maxlength="4" /> <img src="code_num.php" id="getcode_num" title="看不清,點擊換一張" align="absmiddle" /></p> <p><input type="button" class="btn" id="chk_num" value="提交" /></p> </div> <div class="demo">
<h3>2、數字+字母驗證碼</h3> <p>驗證碼:<input type="text" class="input" id="code_char" maxlength="4" /> <img src="code_char.php" id="getcode_char" title="看不清,點擊換一張" align="absmiddle" /></p> <p><input type="button" class="btn" id="chk_char" value="提交" /></p> </div> <div class="demo">
<h3>3、中文驗證碼</h3> <p>驗證碼:<input type="text" class="input" id="code_zh" maxlength="4" /> <img src="code_zh.php" id="getcode_zh" title="看不清,點擊換一張" align="absmiddle" /></p> <p><input type="button" class="btn" id="chk_zh" value="提交" /></p> </div> <div class="demo">
<h3>4、仿google驗證碼</h3> <p>驗證碼:<input type="text" class="input" id="code_gg" maxlength="4" /> <img src="code_gg.php" id="getcode_gg" title="看不清,點擊換一張" align="absmiddle" /></p> <p><input type="button" class="btn" id="chk_gg" value="提交" /></p> </div> <div class="demo">
<h3>5、算術驗證碼</h3> <p>驗證碼:<input type="text" class="input" id="code_math" maxlength="4" /> <img src="code_math.php" id="getcode_math" title="看不清,點擊換一張" align="absmiddle" /></p> <p><input type="button" class="btn" id="chk_math" value="提交" /></p></div>
2、js驗證
$(function() { $("#getcode_num").click(function() { //數字驗證 $(this).attr("src", 'code_num.php?' + Math.random()); }); $("#chk_num").click(function() { var code_num = $("#code_num").val(); $.post("chk_code.php?act=num", { code: code_num }, function(msg) { if (msg == 1) { alert("驗證碼正確!"); } else { alert("驗證碼錯誤!"); } }); });
|
新聞熱點
疑難解答