登录  /  注册
如何利用php生成验证码
迷茫
发布: 2023-03-06 22:46:01
原创
703人浏览过

PHP制作验证码

<?php 
/**
 * php生成验证码
 * @param $width 画布宽
 * @param $height 画布高
 * @param $vcodelen 验证码长度
 * @param $pointnum 干扰像素点数量
 * @param $linenum 干扰线条数量
 *
 * 思路:创建验证码画布,生成并填充背景色,生成验证码内容/干扰像素点/线,填充到画布,输出。
 */
    $width =  100;
    $height = 30;
    $vcodelen = 4;
    $pointnum = 200;
    $linenum = 3;
    // 创建画布
    $image = imagecreatetruecolor($width, $height);
    // 创建色块
    $bgcolor = imagecolorallocate($image, 255, 255, 255);
    // 填充画布背景色
    imagefill($image, 0, 0, $bgcolor);
    // 验证码内容
    for ($i=0; $i < $vcodelen; $i++) { 
        // 字体大小
        $fontsize = 5;
        // 字体颜色,颜色在限定范围内随机
        $fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
        $data = 'abcdefghijklmnopqrstuvwxyz0123456789';
        // 验证码内容在以上字符串内随机截取
        $fontcontent = substr($data, rand(0,strlen($data)),1);
        // 字符串显示位置
        $x = ($i*$width/4)+rand(5,15);
        $y = rand(5,10);
        // 字符串填充图片
        // imagestring的字体大小可选1-5,字体再大需要用imagettftext函数(需要字体文件)
        imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
        // imagettftext($image, $fontsize, 0, $x, $y, $fontcolor, '/font/Geneva.dfont', $fontcontent);
    }
    // 干扰像素点
    for ($i=0; $i < $pointnum; $i++) { 
        $pointcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
        // 画布填充像素点函数
        imagesetpixel($image, rand(0,$width), rand(0,$height), $pointcolor);
    }
    // 干扰线条
    for ($i=0; $i < $linenum; $i++) { 
        $linecolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
        // 画布填充线条函数
        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生成验证码的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学