分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

PHP 生成验证码(+图片没有显示的解决办法)

发布时间:2023-09-06 02:10责任编辑:苏小强关键词:PHP验证码

今天有需要用到验证码,就敲了个,毕竟用途比较广,所以打算把代码留下来,以后肯定用得上的。当然,今天在做的时候也是有一些问题的,分享出来吧,记录自己所犯的错误,避免以后再掉坑里。

先给个效果图(下面的真的是图):

再上完整的代码吧:

 1 <?php 2 ????// 开启 session 3 ????session_start(); 4 ?????5 ????// 丢弃输出缓冲区的内容 ** 6 ????ob_clean(); 7 ?????8 ????// 1 创建画布 9 ????$img = imagecreatetruecolor(100, 30);10 ????11 ????// 2 画一个矩形并填充12 ????$bgcolor = imagecolorallocate($img, mt_rand(120,255), mt_rand(120,255), mt_rand(120,255));13 ????imagefilledrectangle($img, 0, 0, 100, 30, $bgcolor);14 ????15 ????// 3 在画布上进行操作16 ????17 ????// 3.1 定义字符串18 ????$str = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890‘;19 ????20 ????// 3.2 定义变量,存放验证码21 ????$code = ‘‘;22 ????23 ????// 3.2 加载自定义字体24 ????$font_file = ‘./comic.ttf‘;25 ????26 ????// 3.3 生成文字部分27 ????for ($i = 0; $i < 4; $i++) {28 ????????// 定义字体颜色29 ????????$fontcolor = imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));30 ????????31 ????????// 文字内容32 ????????$content = substr($str, mt_rand(0, strlen($str)-1), 1);33 ????????34 ????????// 设置显示坐标35 ????????$x = ($i * 100 / 4) + mt_rand(5, 10);36 ????????$y = mt_rand(17, 22);37 ????????38 ????????// 把文字填充到画布39 ????????imagefttext($img, 15, mt_rand(-5, 5), $x, $y, $fontcolor, $font_file, $content);40 ????????41 ????????// 将文字内容赋值给 code 变量42 ????????$code .= $content;43 ????}44 ????45 ????// 3.4 将大写字母转换为小写46 ????$code = strtolower($code);47 ????48 ????// 3.5 给 session 赋值49 ????$_SESSION[‘code‘] = $code;50 ????51 ????// 3.6 设置干扰元素52 ????for ($i = 0; $i < 200; $i++) {53 ????????$pointcolor = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));54 ????????imagesetpixel($img, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);55 ????}56 ????57 ????// 3.7 设置干扰线58 ????for ($i = 0; $i < 3; $i++) {59 ????????$linecolor = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));60 ????????imageline($img, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $pointcolor);61 ????}62 ????63 ????// 4 向浏览器输出图片头信息64 ????header(‘Content-Type:image/png‘);65 ????66 ????// 5 输出图片到浏览器67 ????imagepng($img);68 ????69 ????// 6 销毁图片70 ????imagedestroy($img);71 ?>

遇到的一个比较严重的问题,也就是我没能独立解决的,就是 ob_clean() 那里(注释上加了俩 * 呢),最初是没有这行代码的。当然,现象就是怎么都刷不出图,看了手册也没找到解决办法,最后还是依赖了度娘,找到了上面的解决办法。(万能的度娘,请收下我的膝盖)

自我感觉注释还是比较详细的吧,反正我看得懂(马马虎虎)。

当然,ob_clean() 并不能解决所有的不能显示的问题,具体问题具体分析,视自己的情况而定。

PHP 生成验证码(+图片没有显示的解决办法)

原文地址:https://www.cnblogs.com/Super-Lee/p/9502058.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved