首页 > 代码库 > php随机产生4位的验证码

php随机产生4位的验证码

<?php
  function getVerify($width=80,$height=30,$type=3,$length=4,$pixel=50,$line=5){
  //创建画布
  $image = imagecreatetruecolor($width,$height);
  //创建画笔白色,用于填充
  $white = imagecolorallocate($image,255,255,255);
  //产生随机色
  function getRandColor($image){
    return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
  }
  //创建填充矩形
  imagefilledrectangle($image,0,0,$width,$height,$white);

  switch($type){
    case 1:
      $str = join(‘‘,array_rand(range(0,9),$length));
    break;
    case 2:
      $str = join(‘‘,array_rand(array_flip(array_merge(range(‘a‘,‘z‘),range(‘A‘,‘Z‘))),$length));
    break;
    case 3:
      $str = join(‘‘,array_rand(array_flip(array_merge(range(0,9),range(‘a‘,‘z‘),range(‘A‘,‘Z‘))),$length));
    break;
    default:
      exit(‘非法参数!!‘);
    break;
    }

    for($i=0;$i<$length;$i++){
      $size = mt_rand(20,24);
      $angle = mt_rand(-15,15);
      $x = imagefontwidth(20) + 20*$i;
      $y = 25;
      $font = ‘fonts/simkai.ttf‘;
      $text = substr($str,$i,1);
      imagettftext($image,$size,$angle,$x,$y,getRandColor($image),$font,$text);
    }

    //添加干扰元素

    if($pixel){
      for($i=0;$i<$pixel;$i++){
        imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
      }
    }

    //添加干扰线段
    if($line){
      for($m=0;$m<$line;$m++){
        imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
      }
    }

  header(‘content-type:image/png‘);
  imagepng($image);
  imagedestroy($image);
  }
  getVerify();

php随机产生4位的验证码