首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 生成可點擊刷新的驗證碼:GD 庫繪製 + JS 時間戳防快取完整範例

     編輯:PHP 相關知識

最輕量的驗證碼實作:PHP GD 繪製 4 碼英數字符,前端 <img> + JS 點擊換圖(附加時間戳查詢字串防瀏覽器快取)。無需 Session、資料庫,適合快速原型或教學示範。

前端頁面 index.html

<html>
<head><title>驗證碼</title></head>
<script>
function refreshCaptcha() {
    var img = document.getElementsByTagName("img")[0];
    img.src = "gd.php?t=" + (new Date().getTime().toString(36));
}
</script>
</head>
<body>
<img src="gd.php" /> <a href="#" onclick="refreshCaptcha()">換一張</a>
</body>
</html>

後端 gd.php

<?php
$im = imagecreate(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$code = '';
for ($i = 0; $i < 4; $i++) {
    $code .= $chars[rand(0, 61)];
}

imagestring($im, 3, rand(10, 20), rand(0, 10), $code, $white);
header("Content-type: image/jpeg");
imagejpeg($im);
imagedestroy($im);
?>

進階建議

  • 生產環境務必將 $code 存入 Session/Redis 驗證
  • 加入干擾線、噪點、字體傾斜、TTF 字體提升強度
  • 考慮使用 Securimage、Gregwar/Captcha 等成熟庫
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved