温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php中怎么实现一个生成验证码函数

发布时间:2021-07-14 15:48:06 来源:亿速云 阅读:128 作者:Leah 栏目:开发技术

php中怎么实现一个生成验证码函数,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

php生成验证码的源码:

<?php 
session_start(); 
//session_register('CheckCode'); 
//PHP4.2以上版本不需要用session_register()注册SESSION变量 
$type='gif'; 
$width= 45; 
$height= 20; 
header("Content-type: image/".$type); 
srand((double)microtime()*1000000); 
if(isset($_GET['action'])){ 
 $randval=randStr(4,$_GET['action']);  
}else{ 
 $randval=randStr(4,''); 
} 
if($type!='gif'&&function_exists('imagecreatetruecolor')){ 
 $im=@imagecreatetruecolor($width,$height); 
}else{ 
 $im=@imagecreate($width,$height); 
} 
$r=Array(225,211,255,223); 
$g=Array(225,236,237,215); 
$b=Array(225,236,166,125); 
$key=rand(0,3); 
$backColor=ImageColorAllocate($im,$r[$key],$g[$key],$b[$key]);//背景色(随机) 
$borderColor=ImageColorAllocate($im,127,157,185);//边框色 
$pointColor=ImageColorAllocate($im,255,170,255);//点颜色 
@imagefilledrectangle($im,0,0,$width - 1,$height - 1,$backColor);//背景位置 
@imagerectangle($im,0,0,$width-1,$height-1,$borderColor); //边框位置 
$stringColor=ImageColorAllocate($im,255,51,153); 
for($i=0;$i<=100;$i++){ 
 $pointX=rand(2,$width-2); 
 $pointY=rand(2,$height-2); 
 @imagesetpixel($im,$pointX,$pointY,$pointColor); 
} 
@imagestring($im,5,5,1,$randval,$stringColor); 
$ImageFun='Image'.$type; 
$ImageFun($im); 
@imagedestroy($im); 
$_SESSION['CheckCode']=$randval; 
function randStr($len=6,$format='ALL'){ 
 switch($format){ 
  case 'ALL'://生成包含数字和字母的验证码 
   $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break; 
  case 'CHAR'://仅生成包含字母的验证码 
   $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; break; 
  case 'NUMBER'://仅生成包含数字的验证码 
   $chars='0123456789'; break; 
  default : 
   $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break; 
 } 
 $string=''; 
 while(strlen($string)<$len) 
 $string.=substr($chars,(mt_rand()%strlen($chars)),1); 
 return $string; 
}

 该函数的具体使用方法请看如下这个示例(这里是生成全数字的验证码):

<img src="checkCode.php?action=NUMBER" width="45" height="20" />

关于php中怎么实现一个生成验证码函数问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI