PHP用GD生成验证码

Standard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-----------validatecode.php------------
<?
//session_start();
function random($len)
{
$srcstr="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
mt_srand();
$strs="";
for($i=0;$i<$len;$i++){
$strs.=$srcstr[mt_rand(0,35)];
}
return strtoupper($strs);
}
$str=random(4); //随机生成的字符串
//$_SESSION["code"] = $str; 也可以用session来做
setcookie("code", $str, time()+60000, "/", ".yemaosheng.com");
$width = 120; //验证码图片的宽度
$height = 35; //验证码图片的高度
@header("Content-Type:image/png");
 
$im=imagecreate($width,$height);
//背景色
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
//字体色
$font=imagecolorallocate($im,287,330,347);
//$font_color=imagecolorallocate($im,287,330,347);
$font_color=imagecolorallocate($im,mt_rand(50,120),mt_rand(50,120),mt_rand(50,120));
//绘模糊作用的点
mt_srand();
for($i=0;$i<500;$i++)
{
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($im,mt_rand(1,255),mt_rand(1,255),mt_rand(1,255)));
}
 
$font_file = $_SERVER['DOCUMENT_ROOT'].'/img/res/font2.ttf';
/*变化文件颜色及角度大小*/
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 5, 30, $font_color, $font_file, substr($str,0,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 35, 30, $font_color, $font_file, substr($str,1,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 65, 30, $font_color, $font_file, substr($str,2,1));
imagettftext($im, mt_rand(15,28), mt_rand(-30,30), 95, 30, $font_color, $font_file, substr($str,3,1));
imagerectangle($im,0,0,$width-1,$height-1,$font); //画边框 int imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col)
imagepng($im);
imagedestroy($im);
?>
-----------html------------
<form name="form1" method="post" action='get.php'>
<input name="validatecode" type="text" value="" /><img src="validatecode.php" />验证码
<input name="submit" type="submit" value="Submit" />
</form>
-----------get.php------------
<?php
if(strtolower($_COOKIE['code'])==strtolower($_POST['validatecode']))
{
echo "ok";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.