php实现图片加法验证码

php 复制代码
<?php
/**
 * Created by PhpStorm.
 * User: finejade
 * Date: 2023-10-19
 * Time: 11:07
 */
session_start(); // 启动Session
require_once('common.php');
session_start();
/*定义头文件为图片*/
header("Content-type: image/png");
/*生成验证码*/
/*创建图片设置字体颜色*/
$w = 70;
$h = 25;
$im = imagecreate($w, $h);
$red = imagecolorallocate($im, 255, 255, 255);
$white = imagecolorallocate($im, 255, 255, 255);
/*随机生成两个数字*/
$num1 = rand(1, 20);
$num2 = rand(1, 20);
$_SESSION ["captcha"] = $num1 + $num2;
/*设置图片背景颜色*/
$gray = imagecolorallocate($im, 118, 151, 199);
$black = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
/*创建图片背景*/
imagefilledrectangle($im, 0, 0, 100, 24, $black);
/*在画布上随机生成大量点*/
for ($i = 0; $i < 80; $i++) {
    imagesetpixel($im, rand(0, $w), rand(0, $h), $gray);
}
/*将计算验证码写入到图片中*/
imagestring($im, 5, 5, 4, $num1, $red);
imagestring($im, 5, 30, 3, "+", $red);
imagestring($im, 5, 45, 4, $num2, $red);
imagestring($im, 5, 70, 3, "=", $red);
imagestring($im, 5, 80, 2, "?", $white);
/*输出图片*/
imagepng($im);
imagedestroy($im);

代码中校验

php 复制代码
	session_start();
    $captcha = isset($_POST['captcha']) ? $_POST['captcha'] : '';
     if ($_SESSION ["captcha"] != $captcha) {
            return error('图形验证码不正确');
        }

前端代码

html 复制代码
<img src="captcha.php" width="70" height="30"  id="valid-img" title="点击再换一张" class="vail_img" alt="验证码图片"/>
js 复制代码
    $("#valid-img").click(function () {
        $(this)[0].src ='captcha.php?'+Math.random();
    })
相关推荐
BingoGo10 小时前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1231 天前
web专题之php代审(二)
php
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
BingoGo1 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt