码迷,mamicode.com
首页 > Web开发 > 详细

PHP之路——验证码实现

时间:2016-09-07 20:46:41      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

验证码生成并保存到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;
	}
 ?>

 

PHP之路——验证码实现

标签:

原文地址:http://www.cnblogs.com/xj76149095/p/5850632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!