PHP之创建图像验证码 ---实例

效果图


PHP页面 code.php


<?php

/*
生成验证码
$n 几个字符
$w 宽度
$h 高度
$size 字体大小
$ttfPath 字体文件路径:硬盘上的绝对路径
*/

createCode(4,80,32,20, "./china.ttf");
 
  function createCode($n,$w,$h,$size,$ttfPath){
       //创建图像资源并定义背景色
        $im=imagecreate($w, $h);
        $backColor=imagecolorallocate($im, 255, 255, 255);
      //生成session中的验证码
        session_start();
        $_SESSION['code']="";

        //定义验证码字符
        $str1="创建图像资源并定义背景色获得验证码字符";
        $str="1a2s3d4f5g6hj8k9qwertyupzxcvbnm";

        for($i=0;$i<$n;$i++){
            //获得验证字符的随机位置
            $start=mt_rand(0,mb_strlen($str,"utf-8"));
            //截取一个字符串
            $s=mb_substr($str, $start,1,"utf-8");

            $fontSize=$size;
            $fontAngle=mt_rand(-20,20);
            $fontColor=imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
          $fontPath=isset($ttfPath)?$ttfPath:"";
          $string=$s;

          //将每个验证码和之前session的内容,组合后,再次覆盖之前session的内容
          $_SESSION["code"]=$_SESSION["code"].$string;

          //获得一个字符的四个角的坐标,8个元素的数组
          $strBox=imagettfbbox($fontSize, $fontAngle, $fontPath, $string);
          $x=($w/$n)*$i;
          $y=$h/2+abs($strBox[1]-$strBox[7])/2;

          //将文本写入图像资源
          imagettftext($im, $fontSize, $fontAngle, $x, $y, $fontColor, $fontPath, $string);         
        }
       //加密
        $_SESSION['code']=md5($_SESSION['code']);

        //加入背景干扰
        for($i=0;$i<3;$i++){
            $bgColor=imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));

            imageline($im, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w), mt_rand(0,$h), $bgColor);           
        }

        header("Content-Type:image/png");
        imagepng($im);
  }

?>


前台HTML页面


<img id="checkpic" οnclick="changing();" src='./code.php' />
<script type="text/javascript">
function changing(){
    document.getElementById('checkpic').src="./code.php?"+Math.random();
}

</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值