打造視覺優雅且機器難識別的驗證碼:使用 TrueType 字型渲染字元、隨機旋轉角度、星星狀干擾點與波浪干擾線,支援不區分大小寫驗證,字型檔需置於 Web 目錄。
<?php
/* @Author fy */
$imgwidth = 100;
$imgheight = 40;
$codelen = 4;
$fontsize = 20;
$charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; // 排除易混淆字元
$font = 'Fonts/segoesc.ttf'; // Win7 內建字型,需上傳至專案
$im = imagecreatetruecolor($imgwidth, $imgheight);
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);
// 生成隨機驗證碼
$authstr = '';
$_len = strlen($charset) - 1;
for ($i = 0; $i < $codelen; $i++) {
$authstr .= $charset[mt_rand(0, $_len)];
}
session_start();
$_SESSION['scode'] = strtolower($authstr); // 統一小寫,不區分大小寫
// 繪製星星干擾點
for ($i = 0; $i < $imgwidth; $i++) {
$randcolor = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagestring($im, mt_rand(1, 5), mt_rand(0, $imgwidth), mt_rand(0, $imgheight), '*', $randcolor);
}
// 繪製水平干擾線
for ($i = 0; $i < $codelen; $i++) {
$randcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($im, 0, mt_rand(0, $imgheight), $imgwidth, mt_rand(0, $imgheight), $randcolor);
}
// 繪製驗證碼字元(隨機水平位移、垂直置中、隨機旋轉 -30~30 度)
$_x = intval($imgwidth / $codelen);
$_y = intval($imgheight * 0.7);
for ($i = 0; $i < strlen($authstr); $i++) {
$randcolor = imagecolorallocate($im, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));
imagettftext($im, $fontsize, mt_rand(-30, 30), $i * $_x + 3, $_y, $randcolor, $font, $authstr[$i]);
}
// 輸出圖片
header("content-type:image/PNG");
imagepng($im);
imagedestroy($im);
?>
imagettftext() 支援反鋸齒、旋轉、精確定位--with-freetype-dir 支援 TTFsegoesc.ttf 需放置於可讀路徑(建議專案內 Fonts/ 目錄)imagepng($im, null, 9) 壓縮等級 9 減少頻寬