当前位置:首页 > PHP

php实现动态验证码

2026-02-27 20:38:56PHP

实现动态验证码的步骤

生成验证码图片

使用GD库创建验证码图片,设置背景色、文字颜色和干扰元素。

// 创建画布
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);

// 设置背景色和文字颜色
$bgColor = imagecolorallocate($image, 240, 240, 240);
$textColor = imagecolorallocate($image, 0, 0, 0);

// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);

// 生成随机验证码
$code = substr(md5(uniqid()), 0, 6);
$_SESSION['captcha'] = $code;

// 绘制验证码文字
imagestring($image, 5, 30, 12, $code, $textColor);

// 添加干扰线
for ($i = 0; $i < 5; $i++) {
    $lineColor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
    imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $lineColor);
}

// 输出图片
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

创建验证码显示页面

创建一个PHP文件专门输出验证码图片,例如captcha.php。

在HTML中调用验证码

在表单页面中通过img标签引用验证码生成脚本。

php实现动态验证码

<img src="captcha.php" onclick="this.src='captcha.php?'+Math.random()" style="cursor:pointer" title="点击刷新验证码">
<input type="text" name="captcha" placeholder="请输入验证码">

验证用户输入

在表单处理页面验证用户输入的验证码是否正确。

session_start();
if ($_POST['captcha'] !== $_SESSION['captcha']) {
    die('验证码错误');
}

增加安全性措施

验证码应设置有效期,通常为5-10分钟。

php实现动态验证码

$_SESSION['captcha_time'] = time();
// 验证时检查时间
if (time() - $_SESSION['captcha_time'] > 600) {
    die('验证码已过期');
}

提高验证码复杂度

可以使用随机字体、扭曲变形或彩色文字增强安全性。

// 使用TrueType字体
$font = 'arial.ttf';
imagettftext($image, 20, rand(-10, 10), 20, 30, $textColor, $font, $code);

// 扭曲变形
imagefilter($image, IMG_FILTER_WAVE, rand(1, 5), rand(10, 50));

防止暴力破解

限制验证码尝试次数,超过次数后锁定或要求重新获取验证码。

if (!isset($_SESSION['attempts'])) {
    $_SESSION['attempts'] = 0;
}
$_SESSION['attempts']++;
if ($_SESSION['attempts'] > 3) {
    die('尝试次数过多,请刷新验证码');
}

标签: 验证码动态
分享给朋友:

相关文章

vue实现微博发布动态

vue实现微博发布动态

Vue 实现微博发布动态功能 数据绑定与表单设计 使用 Vue 的 v-model 实现表单双向绑定,创建动态内容输入框和图片上传组件。示例代码: <template> <d…

vue 实现动态样式

vue 实现动态样式

动态样式绑定方法 在Vue中实现动态样式主要通过v-bind:class和v-bind:style指令完成,以下是具体实现方式: 类名绑定 <div :class="{ active:…

js验证码的实现

js验证码的实现

验证码的基本实现原理 验证码(CAPTCHA)的核心目标是区分人类用户和自动化程序。JavaScript可用于生成或验证客户端验证码,但需注意纯前端验证可能被绕过,通常需结合后端验证。 纯前端验证码…

vue 动态组件实现

vue 动态组件实现

vue 动态组件实现 Vue 的动态组件功能允许根据条件或用户交互动态切换不同的组件,主要通过 <component> 标签和 is 属性实现。 基本用法 通过 is 属性绑定组件名或…

vue 实现动态组件

vue 实现动态组件

Vue 动态组件的实现方法 在 Vue 中,可以通过 <component> 标签结合 is 属性实现动态组件切换。以下是具体实现方式: 使用 is 属性绑定组件名 <templ…

vue 实现动态表单

vue 实现动态表单

Vue 实现动态表单的方法 动态表单通常指表单字段可以动态增减或根据条件变化。以下是几种实现方式: 使用 v-for 动态渲染表单字段 通过数组存储表单字段数据,利用 v-for 动态渲染:…