美文网首页
php生成图片验证码

php生成图片验证码

作者: 他删时 | 来源:发表于2020-04-14 11:13 被阅读0次

以下代码直接运行然后输出到html的img标签的src属性即可

<img src="captcha.php" alt='验证码图片'> 

php代码

<?php
      //如果是在laravel框架中使用
      ob_end_clean();          //不然刷新过快时会有乱码
      //1.创建黑色画布
      $image = imagecreatetruecolor(120, 40);

      //2.为画布定义(背景)颜色
      $bgcolor = imagecolorallocate($image, 255, 255, 255);

      //3.填充颜色
      imagefill($image, 0, 0, $bgcolor);

      // 4.设置验证码内容
      //4.1 随机字符池
      $content = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789";

      //4.1 创建一个变量存储产生的验证码数据,便于用户提交核对
      $captcha = "";
      for ($i = 0; $i < 4; $i++) {
        // 字体大小
        $fontsize = mt_rand(20,24);

        // 字体颜色
        $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

        // 获取随机字符
        $fontcontent = substr($content, mt_rand(0, strlen($content)-1), 1);
        $captcha .= $fontcontent;

        // 在图片中的坐标
        $x = ($i * 108 / 4) + mt_rand(3, 12);
        $y = mt_rand(24, 36);

        // 填充内容到画布中
        //      imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);  //这种方法不能设置字体大小
          //字体文件必须有
            imagettftext( $image, $fontsize, mt_rand(0,16), $x, $y, $fontcolor, '/tmp/fonts/DejaVuSans-Bold.ttf', $fontcontent);
      }

    //验证码内容存入session
      $_SESSION["captcha"] = $captcha;
      $_SESSION["lower_captcha"] = strtolower($captcha);
      $_SESSION["upper_captcha"] = strtoupper($captcha);

      //4.3 设置背景干扰元素
      for ($i = 0; $i < 255; $i++) {
        $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imagesetpixel($image, mt_rand(1, 119), mt_rand(1, 39), $pointcolor);
      }

      //4.4 设置干扰线
      for ($i = 0; $i < 12; $i++) {
        $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imageline($image, mt_rand(1, 119), mt_rand(1, 39), mt_rand(1, 119), mt_rand(1, 39), $linecolor);
      }

      //5.向浏览器输出图片头信息
      header('content-type:image/png');

      //6.输出图片到浏览器
      imagepng($image);

      //7.销毁图片
      imagedestroy($image);

在laravel框架中最好控制器类中加上析构函数

//销毁图片,防止乱码
    public function __destruct()
    {
        imagedestroy($this->image);
        exit();
    }

相关文章

网友评论

      本文标题:php生成图片验证码

      本文链接:https://www.haomeiwen.com/subject/yfjzmhtx.html