您的位置:首页 > 编程语言 > PHP开发

PHP 生成随机的验证码图片

2015-01-13 16:27 591 查看
这是很久之前写的一个PHP 验证码程序,今天把它分享出来:

<?php
/**
 * 生成随机的验证码
 *
 * @access  private
 * @param   integer $length     验证码长度
 * @return  string
 */
session_start();
function generate_word($length = 4)
{
	$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
    //$chars = array("我","验","是","一","九","新","人","有","和","月","朋","折","白","的","笔","禾","主","言","方","产","立","不","水","为","炎");
	if(!is_array($chars)){
		$chars = str_split($chars,1);
	}
	for ($i = 0, $count = count($chars); $i < $count; $i++)
	{
		$arr[$i] = $chars[$i];
	}

	mt_srand((double) microtime() * 1000000);
	shuffle($arr);
	return $arr[rand(0,$count-1)];
}
// 创建图片
$width = 50;
$height = 23;
$im = ImageCreate($width,$height);
// 绘制图片背景
ImageFilledRectangle($im,0,0,$width,$height,imagecolorallocate($im,mt_rand(240,250),mt_rand(240,250),mt_rand(240,250)));

//设置干扰色块:
//定位坐标
$values = array();
for($i=0;$i<=50;$i+=16){//x坐标
   for($j=0;$j<=23;$j+=10){//y坐标
		$values[] = array(
			rand($i,$i+16),rand($j,$j+10),
			rand($i,$i+16),rand($j,$j+10),
			rand($i,$i+16),rand($j,$j+10),
			rand($i,$i+16),rand($j,$j+10),
			rand($i,$i+16),rand($j,$j+10),
			rand($i,$i+16),rand($j,$j+10),
		);
   }
}
// 画多边形色块
for($i=0,$j=count($values);$i<$j;$i++){
    // 设定颜色
    $color = imagecolorallocate($im, rand(180,220),rand(180,220),rand(180,220));
    imagefilledpolygon($im, $values[$i], 6, $color);
}

// 加入干扰象素
for($i=0;$i<70;$i++) {
    imagesetpixel($im, mt_rand(0,$width),rand(0,$height),imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)));
}
// 输出不同颜色的文字
$gen_code = "";
for ($i=3;$i<=37;$i+=11) {
	$rnd = generate_word(1,true,false);
	$gen_code .= $rnd;
	if(ord($rnd)>127){
		imagefttext($im,13,rand(-15,15),$i-3,22,imagecolorallocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)),"courbd.ttf",iconv("UTF-8","UTF-8",$rnd));
	}else{
		imagefttext($im,15,rand(-15,15),$i,18,imagecolorallocate($im,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100)),"courbd.ttf",$rnd);
	}
}
// 输出图片
$_COOKIE["imgcode"] = $gen_code;
header("content-type:image/png;charset=utf-8");
ImagePng($im);
imagedestroy($im);
?>
代码中字体的链接:http://pan.baidu.com/s/1dHtgy

运用:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>
  <img src="image.php" />
 </body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: