現在Web頁面上的表單一般都會內嵌一條驗證碼輸入,以防止伺服器被惡意DoS攻擊或者不法之徒利用機器程式自動貼牛皮癬廣告。
在PHP裡的簡單實現方法如下:
1. 首先在表單頁面展現之前,產生一副圖片,並添加上一些幹擾像素或線段(防止OCR程式自動識別)
再由PHP程式自動產生隨機的待驗證的一串數字和字母組合的字元, 調用imagettftext()函數畫到圖片中,
並把這串字元儲存到Session級變數中。
以下為產生驗證碼的檔案authcode.php (需要php gd庫的支援,否則無法正常顯示驗證碼圖片)
<?php
session_start();
header("Content-type:image/PNG");
srand((double)microtime() * 1000000);
$imagewidth = 60;
$imageheight = 20;
$authimage = imagecreate($imagewidth, $imageheight);
$black = ImageColorAllocate($authimage, 0, 0, 0);
$white = ImageColorAllocate($authimage, 255, 255, 255);
$red = ImageColorAllocate($authimage, 255, 0, 0);
$gray = ImageColorAllocate($authimage, 200, 200, 200);
//背景顏色為灰色
imagefill($authimage, 0, 0, $gray);
//隨機的產生一些幹擾像素
for($i = 0; $i < 400; $i++)
{
$randcolor = ImageColorallocate($authimage, rand(10, 255), rand(10, 255), rand(10, 255));
imagesetpixel($authimage, rand()%$imagewidth, rand()%$imageheight, $randcolor);
}
//隨機的畫幾條線段
for($i = 0; $i < 6; $i++)
{
imageline($authimage, rand()%$imagewidth, rand()%$imageheight,
rand()%$imagewidth, rand()%$imageheight, $black);
}
//產生驗證串
$array = "0123456789abcdefghijklmnopqrstuvwxyz";
for($i = 0; $i < 4; $i++)
{
$authcode .=substr($array, rand(0, 35), 1);
}
imagettftext($authimage, 20, 0, 0, $imageheight, $red, 'arial.ttf', $authcode);
ImagePNG($authimage);
ImageDestroy($authimage);
$_SESSION['authcode'] = $authcode;
?>
2. 在form表單中添加顯示驗證碼圖片
驗證碼:<input type="text" name="authcode" id="textfield"/>
<img src = "authcode.php" /><br />
3. 當使用者提交輸入後,就可以驗證所輸入的驗證碼與伺服器端儲存的驗證碼是否一致。
if(strcmp($_SESSION['authcode'], $_POST['authcode']))
{
echo "<script>alert('驗證碼輸入錯誤!');</script>";
}