php生成图片验证码

以下代码直接运行然后输出到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();
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在生成图片验证码的时候有这么一段代码: //打印出随机数 //dechex — 十进制转换为十六进制0-9 a-f...
    三盏灯亮一盏阅读 240评论 0 0
  • --- 学习目标: - 了解常用浏览器 - 掌握WEB标准 - 理解标签语义化 - 掌握常用的排版标签 ...
    红豆丁244阅读 1,436评论 0 2
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,916评论 0 3
  • 电影《我不是药神》热映,拒绝焦虑,理性规划保险 7月6号,电影《我不是药神》上映,虽然Chad自己还没看,但是网上...
    Chad_Liu阅读 849评论 0 1
  • 前几天看电视听到了一段话。说普通人的幸福生活就是每天睡觉睡到自然醒,数钱数到手抽筋。而现实是睡觉睡到手抽筋,数钱数...
    彧瑛阅读 187评论 0 4

友情链接更多精彩内容