代码改变世界

php 产生验证码

2012-03-11 21:52  youxin  阅读(318)  评论(0编辑  收藏  举报
<?php 
session_start();
header("Content-type:image/png");
srand((double)microtime()*1000000);
$imagewidth=160;
$imageheight=40;
$image=imagecreate($imagewidth,$imageheight);
$background_color=imagecolorallocate($image,200,200,200); //gray
$white = imagecolorallocate($image, 255, 255, 255);
$black=imagecolorallocate($image,0,0,0);
$red = imagecolorallocate($image, 255, 0, 0);
$font = 'arial.ttf';

//随机生成一些干扰的像素
for($i=0;$i<400;$i++)
{
$randcolor=imagecolorallocate($image,rand(10,255),rand(10,255),rand(10,255));
imagesetpixel($image,rand()%$imagewidth,rand()%$imageheight,$randcolor );

}
//随机的画几条线段
for($i=0;$i<6;$i++)
{
imageline($image,rand()%$imagewidth,rand()%$imageheight,rand()%$imagewidth,rand()%$imageheight,$black);
}

//生成验证字符串
$array="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$authcode=''; //不写这行有错误,unexpected );expected ;
for($i=0;$i<4;$i++)
{
$authcode.=substr($array,rand(0,67),1);
}

//imagettftext($image,2,0,0,0,$red,'arial ttf',$authcode); //显示不出图片啊,不知道什么原因。
//imagettftext($image, 20, 0, 10, 20, $red,$font,$authcode); 还是错

imagestring($image,5,40,15,$authcode,$red); //font 是 1,2,3,4 或 5
imagepng($image);
imagedestroy($image);
$_SESSION['authcode']=$authcode;

?>