使用php制作验证码技术

这个函数是用来产生验证码所需的字符串。原理,首先把字母数字整合到一起,然后使用str_shuffle函数将字符串打乱,然后截取所需要的长度返回。

<?php

/*
 * 函数说明,使用这个函数,返回不同的类型,或者是不同长度的字符串,用来制作验证码
 * 
 * */
function buildRandomString($type=1,$length=4)
{
    if($type==1)
    {
        //纯数字验证码,join将数组转换为字符串 range分布的意思
        $chars=join("",range(0,9));
    }
    else if($type==2)
    {
        //array_merge() 将几个数组合为一个
        $chars=join("",array_merge(range("a","z",range("A","Z"))));
    }
    else if($type==3)
    {
        $chars=join("",array_merge(range("a","z",range("A","Z"),range(0,9))));
    }
    if($length>strlen($chars))
    {
        exit("长度过长了");
    }
    //字符串打乱函数
    $chars=str_shuffle($chars);
    return substr($chars,0,$length);
}

?>

用来制作验证码的部分

<?php
//制作画布
  require_once 'string.func.php';
  header("Content-type:image/png");
  $width=180;
  $height=28;
//设置颜色
  $image=imagecreatetruecolor($width, $height);
  $white=imagecolorallocate($image,255,255,255);
  $black=imagecolorallocate($image,0,0,0);
  imagefilledrectangle($image,1,1,$width-2,$height-2,$black);
  //ImageFill($image,0,0,$white);
  //ImageLine($image,10,10,90,40,$black);
//类型是1,长度是8
  $type=1;
  $length=8;
//根据类型和长度设置验证码
  $chars=buildRandomString($type,$length);
  $sess_name="verify";
  $_SESSION[$sess_name]=$chars;
//制作验证码需要的字体文件
  $fontfiles=array("MSYH.TTF","MSYHBD.TTF","SIMFANG.TTF","SIMHEI.TTF","SIMKAI.TTF","SIMSUN.TTC");
  for($i=0;$i<$length;$i++)
  {
      //大小,角度,和字体的类型都可以任意制定
      $size=mt_rand(14,18);
      $angle=mt_rand(-15,15);
      $x=5+$i*$size;
      $y=mt_rand(20,26);
      $fontfile="../fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)];
      $color=imagecolorallocate($image,mt_rand(50,90),mt_rand(80,200),mt_rand(90,100));
      $text=substr($chars, $i,1);
      imagettftext($image,$size, $angle, $x, $y, $color, $fontfile, $text);
  }
  Imagepng($image);
  //记得释放资源
  ImageDestroy($image);
?>

最终结果,可以得到所需长度所需类型以及所需字体的验证码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值