PHP之路——验证码实现

验证码生成并保存到session

<?php
	//开始session
	session_start();
	//画布大小
	$image = imagecreate(100, 40);
	$color = imagecolorallocate($image, 255, 255, 255);
	// imagefill($image,0, 0, $color);

	//创建验证码
	$code = '';
	for($i=0;$i<4;$i++){
		$fontsize = 9;
		$fontcolor = imagecolorallocate($image, rand(0,120), rand(0,120), rand(0,120));
		$x = $i * 25 + 10;
		$y = rand(5,10);
		$num = (string)rand(0,9);
		$code .= $num;
		imagestring($image, $fontsize, $x, $y, $num, $fontcolor);
	}
	//验证码记录到session
	$_SESSION['code'] = $code;

	//增加干扰元素点
	for ($i=0; $i <800 ; $i++) { 
		$color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
		imagesetpixel($image, rand(0,100), rand(0,40), $color);
	}

	//增加干扰线
	for ($i=0; $i <5 ; $i++) { 
		$color = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
		imageline($image, rand(10,180), rand(10,180), rand(10,180), rand(10,180), $color);
	}
	//说明这个是一个图片
	header("content-type:image/png");
	//输出到浏览器
	imagepng($image);
	//关闭
	imagedestroy($image);

 

html文件

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title></title>
</head>
<body>
<div><img src="yzimg.php" width="100" height="40" id="yzimg" onclick="huan()"></div>
<div><input type="text" id="yzm"></input></div>
<button id="btn">提交</button>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
	function huan(){
		var num = Math.random() * 10;
		document.getElementById('yzimg').src = 'yzimg.php?r=' + num;
	}
	$('#btn').click(function(){
		$.post(
				'/yzm/yz.php',
				{'yzm':$('#yzm').val()},
				function(data){
					if (data == 0) {
						alert('YES');
					} else {
						alert('NO');
						huan();
					}
				}
			)
	})
</script>
</body>
</html>

 

验证验证码文件

<?php 
	//必须开启session
	session_start();
	if ($_POST['yzm'] != $_SESSION['code']) {
		# code...
		echo 1;
	} else {
		echo 0;
	}
 ?>

 

posted @ 2016-09-07 19:28  偏执Dog  阅读(2212)  评论(0编辑  收藏  举报