後端:驗證碼類別 lib_captcha.php
<?php
class Captcha_code {
public $width = 60;
public $num = 4;
public $height = 20;
public $name = 'randcode';
public function __construct($config = []) {
foreach ($config as $key => $val) {
if (property_exists($this, $key)) $this->$key = $val;
}
}
public function show() {
header("Content-Type: image/gif");
$border = 0;
$how = $this->num;
$w = $this->width;
$h = $this->height;
$fontsize = 5;
$alpha = 'abcdefghijkmnopqrstuvwxyz'; // 排除 l 混淆
$number = '023456789'; // 排除 1 混淆
$randcode = '';
$im = imagecreatetruecolor($w, $h); // 建議用 TrueColor
// 背景
$bg = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $bg);
// 邊框
if ($border) {
$black = imagecolorallocate($im, 0, 0, 0);
imagerectangle($im, 0, 0, $w-1, $h-1, $black);
}
// 繪製字符
for ($i = 0; $i < $how; $i++) {
$useAlpha = mt_rand(0, 1);
$pool = $useAlpha ? $alpha : $number;
$char = $pool[mt_rand(0, strlen($pool)-1)];
$x = $i === 0 ? 4 : $x + 15;
$color = imagecolorallocate($im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100));
imagechar($im, $fontsize, $x, 3, $char, $color);
$randcode .= $char;
}
// 干擾線
for ($i = 0; $i < 5; $i++) {
$color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagearc($im, mt_rand(-5,$w), mt_rand(-5,$h), mt_rand(20,300), mt_rand(20,200), 55, 44, $color);
}
// 干擾點
for ($i = 0; $i < $how * 15; $i++) {
$color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
imagesetpixel($im, mt_rand(0,$w), mt_rand(0,$h), $color);
}
// 寫入 Session
$_SESSION[$this->name] = $randcode;
// CI 寫法:$this->session->set_userdata([$this->name => $randcode]);
imagegif($im);
imagedestroy($im);
}
}
控制器調用
public function verify_image() {
$config['name'] = 'verify_code';
$this->load->library('lib_captcha', $config);
$this->lib_captcha->show();
// 除錯:顯示 session 值
// echo $this->session->userdata('verify_code');
}
前端視圖
<dl>
<dt>驗證碼:</dt>
<dd>
<input type="text" name="verify_text" id="verify_text" class="yzma" value="">
<img src="/user/verify_image" alt="驗證碼" id="verify_code" class="yz_img">
<a href="javascript:changeCode();" class="change_yz">換一張</a>
</dd>
<dd class="tips_wrong"><b>驗證碼不正確</b></dd>
<dd class="tips_correct"></dd>
</dl>
JavaScript 切換驗證碼
<script>
function changeCode() {
// 加隨機參數防止瀏覽器快取圖片
document.getElementById('verify_code').src = "/user/verify_image?r=" + Math.random();
}
</script>
表單驗證(控制器)
public function submit() {
$input = $this->input->post('verify_text');
$sess = $this->session->userdata('verify_code');
if (strtolower($input) !== strtolower($sess)) {
$this->form_validation->set_message('verify_text', '驗證碼錯誤');
return false;
}
// 通過驗證,處理業務邏輯
}
改進建議
- 使用
imagecreatetruecolor() 替代 ImageCreate()(支援真彩色)
- 字符集排除易混淆字元(0/O, 1/l/I, 2/Z 等)
- 加入 Session 過期時間控制
- 考慮使用成熟套件:
gregwar/captcha (Composer)
- 生產環境建議啟用 GD/Freetype 並使用 TTF 字體(
imagettftext())提升可讀性與安全性