学习使用php实现汉字验证码

学习使用php实现汉字验证码

php 复制代码
<?php
//开启session ,方便验证
session_start();
//创建背景画布
$image = imagecreatetruecolor(200, 60);
$background = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $background);

//创建背景画布
for ($i = 0; $i < 300; $i++) {
    $pixColor = imagecolorallocate($image, rand(150, 240), rand(150, 240), rand(150, 240));
    $pixX = rand(10, 190);
    $pixY = rand(5, 55);
    imagesetpixel($image, $pixX, $pixY, $pixColor);
}

//4条水平线
for ($i = 0; $i < 5; $i++) {
    $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150));
    $lineX1 = 0;
    $lineX2 = 300;
    $lineY1 = ($i + 1) * 12;
    $lineY2 = ($i + 1) * 12;
    imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor);
}
//10条垂直线
for ($i = 0; $i < 30; $i++) {
    $lineColor = imagecolorallocate($image, rand(50, 150), rand(50, 150), rand(50, 150));
    $lineX1 = ($i + 1) * 10;
    $lineX2 = ($i + 1) * 10;
    $lineY1 = 0;
    $lineY2 = 60;
    imageline($image, $lineX1, $lineY1, $lineX2, $lineY2, $lineColor);
}

//汉字库
$text_str = '君|不|见|黄|河|之|水|天|上|来|奔|流|到|海|不|复|回|君|不|见|高|堂|明|镜|悲|白|发|朝|如|青|丝|暮|成|雪|人|生|得|意|须|尽|欢|莫|使|金|樽|空|对|月|天|生|我|材|必|有|用|千|金|散|尽|还|复|来|烹|羊|宰|牛|且|为|乐|会|须|一|饮|三|百|杯|岑|夫|子|丹|丘|生|将|进|酒|杯|莫|停|与|君|歌|一|曲|请|君|为|我|倾|耳|听|钟|鼓|馔|玉|不|足|贵|但|愿|长|醉|不|愿|醒|古|来|圣|贤|皆|寂|寞|惟|有|饮|者|留|其|名|陈|王|昔|时|宴|平|乐|斗|酒|十|千|恣|欢|谑|主|人|何|为|言|少|钱|径|须|沽|取|对|君|酌|五|花|马|千|金|裘|呼|儿|将|出|换|美|酒|与|尔|同|销|万|古|愁';

$text = explode('|', $text_str);

$text_count = bcsub(count($text), 1);

//创建背景画布
$text_new = '';
for ($i = 0; $i < 4; $i++) {
    $textColor = imagecolorallocate($image, rand(20, 100), rand(20, 100), rand(20, 100));
    $textX = $i * 50 + 10;
    $textY = rand(40, 60);
    //随机生成数字
    $rand_i = rand(0, $text_count);
    $text_new .= $text[$rand_i];
    imagettftext($image, 30, rand(20, 50), $textX, $textY, $textColor, "simhei.ttf", $text[$rand_i]);
}
//存入session
$_SESSION['text_new'] = $text_new;

header("Content-Type:image/png");
imagepng($image);

?>

效果图

相关推荐
寒秋花开曾相惜15 分钟前
(学习笔记)4.1 Y86-64指令集体系结构(4.1.4 Y86-64异常&4.1.5 Y86-64程序)
开发语言·jvm·数据结构·笔记·学习
莹宝思密达30 分钟前
【AI学习】 playwright-cli + SKILL 替换 chrom-devTools-MCP
学习
cyr___42 分钟前
Unity教程(二十七)技能系统 黑洞技能(下)黑洞状态
学习·游戏·unity·游戏引擎
豆瓣鸡2 小时前
Gradle学习
学习
海绵宝宝的月光宝盒3 小时前
2-非金属材料
经验分享·笔记·学习·其他·职场和发展·课程设计·制造
小饕3 小时前
RAG学习之- RAG 数据导入完整指南
人工智能·python·学习
cyr___4 小时前
Unity教程(二十六)技能系统 黑洞技能(上)基础实现
学习·游戏·unity·游戏引擎
星幻元宇VR4 小时前
VR党建蛋椅|以沉浸式体验推动党建学习方式创新
科技·学习·安全·vr·虚拟现实
大学生小郑5 小时前
如何定义图像质量,如何评价图像质量
图像处理·学习·音视频·视频
三品吉他手会点灯5 小时前
C语言学习笔记 - 9.C概述 - 常见问题答疑
c语言·笔记·学习