发一个用PHP写的随机验证码程序。源码实现:PHP session + PHP img。代码有详细的注释,便于研究。
a.php代码: <?php session_start(); //构造随机字符串函数,参数$len为字符串的长度 function random($len) { $srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; mt_srand(); $strs=""; for($i=0;$i<$len;$i++){ $strs.=$srcstr[mt_rand(0,35)]; } return strtoupper($strs); } $str=random(6); //随机生成的字符串 $_SESSION["code"] = $str; //将字符串保存到session里 echo "<img src='b.php' border='0' align='absbottom'>";//生成图片 echo $_SESSION["code"];//生成验证码值 ?> b.php代码: <?php session_start(); @header("Content-Type:image/png"); //设置header格式为png格式 $Code = $_SESSION['code']; //页面传递过来的随机验证码 $width = 191; //验证码图片的宽度 $height = 68; //验证码图片的高度 $img=imagecreate($width,$height); $back=imagecolorallocate($img,0xFF,0xFF,0xFF); //背景色 $pix=imagecolorallocate($img,187,230,247); //模糊点颜色 $fontColor=imagecolorallocate($img,41,163,238); //字体色 $fontType='C:\Windows\Fonts\simhei.ttf'; //设置字体样式,这里是黑体 mt_srand(); //绘模糊作用的点 for($i=0;$i<1000;$i++) { imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pix); } imagettftext($img, 35, 0, 25, 52, $fontColor, $fontType, $Code); imagerectangle($img,0,0,$width-1,$height-1,$fontColor); imagepng($img); imagedestroy($img); ?>
|