zoukankan      html  css  js  c++  java
  • 原生PHP生成验证码

    <?php
    //生成随机的字符串
        function get_str($len = 4)
        {
            $char = "1234567890abcdefghijklmnoqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ";
            $str = str_shuffle($char); //将字符串打乱
            $str = substr($str, 0, $len); //截取四位字符串
            return $str;
        }
    
    //验证码函数
        function img_code($width = 76, $height = 30)//1.定义验证码宽高默认值
        {
            
    //2.创建
            $img = imagecreatetruecolor($width, $height);
            
    //3.验证码添加背景颜色和文字颜色---imagecolorallcoate()
            $bgcolor = imagecolorallocate($img, 200, 200, 200);
            $textcolor = imagecolorallocate($img, 255, 0, 0);
            
    //4.指定图片上画矩形---imagefilledrectangle()
            imagefilledrectangle($img, 0, 0, $width, $height, $bgcolor);
            
    //5.将文字放入图片
            $code = get_str();
            imagestring($img, 5, 20, 5, $code, $textcolor);
            
    //6.图片上面加一些点
            for ($i = 0; $i < 30; $i++) {
                $dotcolor = imagecolorallocate($img, mt_rand(0, 155), mt_rand(0, 155), mt_rand(0, 155));
                imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), $dotcolor);
            }
            
    //7.画线
            for ($i = 0; $i < 2; $i++) {
                $linecolor = imagecolorallocate($img, mt_rand(0, 155), mt_rand(0, 155), mt_rand(0, 155));
                imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $linecolor);
            }
            
    //将验证码存入session
            session_start();
            $_SESSION['imgcode'] = strtolower($code);
            
    //输出图像
            header('Content-Type:image/jpeg');
            imagejpeg($img);
            
    //销毁图像,释放内存
            imagedestroy($img);
        }
    //调用验证码函数查看验证码
        img_code();
  • 相关阅读:
    在循环中禁止remove/add
    [算法竞赛入门]WERTYU
    [算法竞赛入门]Tex Quotes
    [算法竞赛入门]竖式问题
    [算法竞赛入门]蛇形填数
    [C++面试]关于const的使用方法
    [C++面试]单例模式-设计模式
    [C++面试]C++的三种继承(public/protected/private继承)
    用微服务架构,有哪些好处?
    东软数据可视化分析, 已经方便成这样?!
  • 原文地址:https://www.cnblogs.com/wxdindex/p/11265641.html
Copyright © 2011-2022 走看看