WEB_PHP_PHP验证码功能实现;

验证码实现代码
/// Login.php 登录页面
<html>
	<head>
		<title>登录页面</title>
		<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	</head>
	<h1>用户登录</h1>
	<form action="LoginProcess.php" method="post">
		<table>
			<tr><td>u:</td><td><input type="text" name="username"/></td><td></td></tr>
			<tr><td>p:</td><td><input type="password" name="password"/></td><td></td></tr>
			<tr><td>验证码:</td><td><input type="text" name="checkcode"/></td><td><img src="checkCode.php" οnclick="this.src='checkCode.php?r='+Math.random()" /></td></tr>
			<tr><td><input type="submit" value="登录"/></td>
			<td colspan="2"><input type="reset" value="重新填写"/></td></tr>
		<table>
	</form>
</html>
/// CheckCode.php 验证码
<?php
//	echo rand(2,9);
//	echo "<br/>".dechex(rand(1,15))."<br/>";
	
	session_start();
	$checkCode="";
	for($i=0;$i<4;$i++){	// 4位验证码
		$checkCode.=dechex(rand(1,15));	// 十进制 转化成 十六进制;
	}

	// 将随机验证码保存到session中
	$_SESSION['myCheckCode']=$checkCode;

	/// 创建图片,并把随机数画上去
	$img=imagecreatetruecolor(110,30);

	// 背景默认就是黑色,你可以指定背景颜色
	$bgcolor=imagecolorallocate($img,0,0,0);
	imagefill($img,0,0,$bgcolor);

	// 创建新颜色
	$white=imagecolorallocate($img,255,255,255);
	$blue=imagecolorallocate($img,0,0,255);
	$red=imagecolorallocate($img,255,0,0);
	$green=imagecolorallocate($img,255,0,0);

	// 画出干扰线段
	for($i=0;$i<20;$i++){
		/*switch(rand(1,4)){
			case 1:
				imageline($img,rand(0,110),rand(0,30),rand(0,110),rand(0,30),$green);
				break;
			case 2:
				imageline($img,rand(0,110),rand(0,30),rand(0,110),rand(0,30),$blue);
				break;
			case 3:
				imageline($img,rand(0,110),rand(0,30),rand(0,110),rand(0,30),$green);
				break;
			case 4:
				imageline($img,rand(0,110),rand(0,30),rand(0,110),rand(0,30),$red);
				break;
		}*/

		// 更好的方法是颜色随机
		imageline($img,rand(0,110),rand(0,30),rand(0,110),rand(0,30),imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255)));
		
	}

	//把四个随机值画上去	
	imagestring($img,rand(1,5),rand(2,80),rand(2,10),$checkCode,$white);
	
	//如果要使用中文
	//考虑array imagefttext ()函数;
	//imagettftext($img,15,10,20,25,$white,"STXINWEI.TTF","北京你好");
	
	//输出
	header("content-type: image/png");
	imagepng($img);
	
	// 摧毁
	imagedestroy($img);
?>
/// LoginProcess.php
<?php
	//启用session
	session_start();

	//获取session中保存的验证码
	$checkCodeInSession=$_SESSION["myCheckCode"];
	
	//获取用户输入
	$checkCode=$_POST["checkcode"];
	if($checkCode==$checkCodeInSession){
		echo "ok";
	}else{
		echo "nook";
	}
?>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值