萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 圖形驗證碼完整實作(authpage.php + authimg.php)

提供一組完整可執行的 PHP 圖形驗證碼範例,包含驗證邏輯頁面(authpage.php)與動態生成圖片腳本(authimg.php)。驗證碼為四位數字,干擾像素增加辨識難度。

authpage.php - 主頁面與驗證邏輯

<?php
srand((double)microtime() * 1000000);

if (isset($_POST['authinput'])) {
    if (strcmp($_POST['authnum'], $_POST['authinput']) == 0)
        echo "驗證成功!";
    else
        echo "驗證失敗!";
}

// 產生 1000-9999 四位數
while (($authnum = rand() % 10000) < 1000);
?>
<form action="authpage.php" method="post">
  <table>
    請輸入驗證碼:<input type="text" name="authinput" style="width:80px"><br>
    <input type="submit" name="驗證" value="提交驗證碼">
    <input type="hidden" name="authnum" value="<?php echo $authnum; ?>">
    <img src="authimg.php?authnum=<?php echo $authnum; ?>">
  </table>
</form>

authimg.php - 動態生成驗證碼圖片

<?php
header("Content-type: image/PNG");
srand((double)microtime() * 1000000);

$im = imagecreate(58, 28);
$black = ImageColorAllocate($im, 0, 0, 0);
$white = ImageColorAllocate($im, 255, 255, 255);
$gray  = ImageColorAllocate($im, 200, 200, 200);

imagefill($im, 68, 30, $gray);
imagestring($im, 5, 10, 8, $_GET['authnum'], $white);

// 加入 50 個干擾像素
for ($i = 0; $i < 50; $i++) {
    imagesetpixel($im, rand() % 70, rand() % 30, $gray);
}

ImagePNG($im);
ImageDestroy($im);
?>

改進方向

  • 使用 TTF 字體(imagettftext())替換內建字體,提升美觀與辨識度。
  • 加入噪點線條、背景雜訊、字元旋轉/扭曲,強化反機器辨識能力。
  • 驗證碼存入 Session 而非隱藏欄位,防止前端竄改。
  • PHP 7+ 建議用 random_int() 取代 rand()。
copyright © 萬盛學電腦網 all rights reserved