PHP验证码

<span style="font-family: Arial, Helvetica, sans-serif;"><?php</span>
	session_start();

	function getCode($num){
		//去掉了 0 1 O l
		$src='23456789abcdefghigkmnpqrstuvwxyz';
		$code='';
		for($i=0;$i<$num;$i++){
			$code.=$src[mt_rand(0,strlen($src)-1)];
		}

		$im_x=60;
		$im_y=20;
		$im=@imagecreatetruecolor($im_x, $im_y) or die('Cannot Initialize new GD image stream');
		$background=imagecolorallocate($im, mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
		$bgd_tmp=imagecolorallocate($im, mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
		imagefill($im, 0, 0, $bgd_tmp);

		//在画布上随机生成大量点,起干扰作用;
		for ($i = 0; $i < 80; $i++) {
		imagesetpixel($im, rand(0, $im_x), rand(0, $im_y), $background);
		}
		//将字符随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成
		$strx = rand(3, 8);
		for ($i = 0; $i < $num; $i++) {
			$strpos = rand(1, 6);
			imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $background);
			$strx += rand(8, 14);
		}
		header("Content-type: image/png");
		imagepng($im);
		imagedestroy($im);
	}
	getCode(4);
?>
建立前端html页,使用ajax输出验证码

<img src="code_num.php" id="getcode" title="看不清,点击换一张"></p> 

相应的js函数代码为

$(function(){ 
    $("#getcode").click(function(){ 
        $(this).attr("src",'code_num.php?' + Math.random()); 
    }); 
    ... 
}); 

以上为实现验证码输出至html页面和点击验证码图片实现刷新验证码部分代码

</pre>PHP GD库 生成字母加数字混合验证码过程1.随机产生4位随机验证码字符串2.使用GD函数画一幅图片3.验证码字符串写入图片4.输出前端<pre name="code" class="php">


PHP 相关函数

mt_rand()使用 Mersenne Twister 算法返回随机整数。


header()函数 指定发送给客户端的头信息
作用:1.页面跳转 2.指定网页内容 3.附件(可用于指定内容为附件,需要保存)
必须在任何实际的输出被发送之前调用 header() 函数

imagecreatetruecolor ( int $width , int $height ) 创建一个真彩色图像


imagecolorallocate ( resource $image , int $red , int $green , int $blue )代表了由给定的 RGB 成分组成的颜色
第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色,即用 imagecreate()或imagecreatetruecolor() 建立的图像


imagefill ( resource $image , int $x , int $y , int $color )
imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)


imagesetpixel ( resource $image , int $x , int $y , int $color ) 画一个单一像素


imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col ) 水平画一行字符串
PHP内置 font位1-5,若需要更大字体,可使用自有字体文件
posted @ 2015-03-20 16:28  SEC.VIP_网络安全服务  阅读(90)  评论(0编辑  收藏  举报