• PHP.19-验证码生成


                        生成验证码

    思路:先定义验证码函数getCode()

    //绘制验证码
      $num = 4; //字符长度
      getCode($num, 2);

      1、创建画布,分配颜色 imagecreatetruecolor()
        $height 
        $width = $num*20;    //假设每个字的大小为18
        $im = imagecreatetruecolor($width, $height); //创建一个真彩色画布
        $bg = imagecolorallocate($im, rand(200,250), rand(250,255), rand(150, 255)); //定义背景颜色图像
        $color[] = imagecolorallocate($im, 240,240,240); //定义字体颜色【可以数组形式存储,定义某些深色字体】
        

      2、开始绘画(一切都在画布$im上进行)
        imagefill($im, 0,0, $bg);    //区域填充(把背景填充到画布)
        imagerectangle($im, 0,0, $width-1, $height-1, $color[rand(0,3)]); //定义个边框

        //绘制验证码:逐字输出
        for()
          imagettftext($im, rand(16,18), rand(-40,40), 8+(18*$i),18, $color[rand(0,3)], "msyh.ttc", $str[$i]);
        //随机添加干扰点(点数自定)
        for(){
          $c = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); //干扰点颜色
          imagesetpixel($im, rand(0,$width), rand(0,$height), $c);
        //随机添加干扰线(线数自定)
        for(){
          $c = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); //干扰线颜色
          imageline($im, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $c);

      3、输出图像
        header("Content-Type:image/png"); //设置响应头(此前不能有输出
        imagepng($im);


      4、销毁图片
        imagedestroy($im);

    //自定义函数,获取验证码
      function getCode($m=4, $type=1)
      {
        $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $t = array(9, 35, strlen($str)-1); //类型划分
        $c = "";
        for($i=0; $i<$m; $i++)
        $c .= $str[rand(0, $t[$type])];

    //调用验证码,onclick可实现点击图片刷新

      <img src="code.php" /onclick="this.src='code.php?id='+Math.random()'">

  • 相关阅读:
    DNS 查询长度
    WebSocket
    Overview of cookie persistence
    Linux Cluster
    keepalived + nginx 主主模式
    MIME 类型
    IaaS,PaaS,SaaS 的区别
    Linux下"负载均衡+高可用"集群的考虑点 以及 高可用方案说明(Keepalive/Heartbeat)
    交换机链路聚合与Linux的bond模式对照
    DHCP 中继
  • 原文地址:https://www.cnblogs.com/zixuanfy/p/6705762.html
Copyright © 2020-2023  润新知