驗證碼是防止機器人提交表單的常見手段。本文示範如何結合 jQuery 與 s3captcha,做出一個「依提示選出正確水果」的圖形驗證碼。s3captcha 原本以 PHP 實現,但很容易移植到 ASP.NET 與 C#。
s3captcha 的核心流程是:
1. 隨機生成圖片的索引;
2. 把一組隨機數據賦給圖片索引;
3. 從圖片列表中選出一個隨機索引作為正確答案;
4. 讓圖片以 radio box 的形式隨機顯示。
它透過 jQuery 實現 radio box 到圖片列表的轉換。
首先是把圖片索引數組順序打亂的洗牌函數:
public static List<int> shuffle(List<int> input)
{
List<int> output = new List<int>();
Random rnd = new Random();
int FIndex;
while (input.Count > 0)
{
FIndex = rnd.Next(0, input.Count);
output.Add(input[FIndex]);
input.RemoveAt(FIndex);
}
return output;
}
用 XML 作為配置文件,定義水果名稱、標題、尺寸與提示訊息:
<s3capcha>
<icons>
<name>apple,cherry,lemon,pear,strawberry</name>
<title>Apple,Cherry,Lemon,Pear,Strawberry</title>
<width>33</width>
<height>33</height>
<ext>jpg</ext>
<folder>fruit</folder>
</icons>
<message>Verify that you are a human not robot, please choose {0}</message>
</s3capcha>
接著透過 ashx 處理程式生成 HTML 並在伺服器端記錄正確答案,再用另一個 ashx 驗證使用者選擇。最後用 jQuery 的 ajax 實現驗證的彈出提示:
$(document).ready(function() {
getCapcha();
$("form").bind('submit', function() {
$.ajax({
url: 'verify.ashx',
type: 'POST',
data: { 's3capcha': $("input[name=s3capcha]:checked").val() },
cache: false,
success: function(data) {
alert(data);
getCapcha();
}
});
return false;
});
});
這套方案把正確答案存在伺服器 Session 中,使用者提交時再由後端比對,兼顧了安全性與友善的圖形化操作,是很實用的驗證碼替代方案。