PHP验证码显示与验证

Captcha 验证码
 session 技术。
 php 处理图片的技术。
 仿照:
 1, 有已存在的背景图几张
 2, 随机得到某张!
 3, 白色边框
 4, 随机文字(大写+数字,黑白随机)
步骤1:确定随机背景图片、基于该背景图片,创建画布!、绘制边框
步骤2:写验证码写到 画布上利用函数imagestring()
  imagestring(画布,字体大小,位置 X,Y,字符串,颜色);
  其中 imagestring 典型的是使用内置字体! (不支持中文) 。字体大小 1-5.5 最大!
步骤3:将验证码展示到页面上

tip:开启 gd 库!
tip:挑错:
 如果向浏览器发送的是图片,则如果有错误浏览器显示:
 直接请求生成图片的 url:108.php。
 此时,将 header(‘Content-Type:image/jpeg’)先注释!
tip:
 典型的错误,一个生成图片的 php 脚本内的任何输出,都会当作图片内容去看!

 

//1.CaptchaTool.class.php

<?php
class CaptchaTool{

	/**
	 *	生成验证码
	 */
	public function generate(){
		ob_end_clean(); // 清除缓存  服务器级缓存的问题
		$randImgFile = TOOL_DIR . 'code/bg' . mt_rand(1,9) . '.jpg';
		// 创建画布
		$codeImg = imagecreatefromjpeg($randImgFile);
		$white = imagecolorallocate($codeImg, 0xff, 0xff, 0xff);
		//不填充矩形
		imagerectangle($codeImg, 0, 0, 145, 30, $white);

		$codeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
		$catpchaStr = '';
		for($i=1,$strlen=strlen($codeChars);$i<=4;++$i){
			$randKey = mt_rand(0,$strlen-1);
			$catpchaStr .= $codeChars[$randKey];
		}
		//保存到session中
		@session_start();
		$_SESSION['captcha_code'] = $catpchaStr;
		$black = imagecolorallocate($codeImg, 0, 0, 0);
		if(mt_rand(0,1) == 1){
			$strColor = $white;
		}else{
			$strColor = $black;
		}
		imagestring($codeImg, 5.5, 50, 8, $catpchaStr, $strColor);
		//

		header('Content-Type: image/jpeg; charset=utf-8');
		//header("Content-Type:text/html;charset=utf-8");
		// 保存与关闭资源
		imagejpeg($codeImg);
		imagedestroy($codeImg);
	}
	/**
	 *	验证验证码
	 */
	public function checkCap($code){
		@session_start();
		return $code == $_SESSION['captcha_code'];
	}
}

?>


 

 

 

//2.后台验证

$captchaTool = new CaptchaTool; // 验证码
if(!$captchaTool->checkCap($_POST['captcha'])){
	$this->skip('index.php',"验证码不正确!",3);
}else{
}


 

 

 

 

//3.前台显示

<tr>
<td>验证码:</td>
<td><input type="text" name="captcha" class="capital" /></td>
</tr>
<tr>
<td colspan="2" align="right">
<img src="index.php?p=admin&c=Admin&a=captcha" width="145" height="20" 
	style="cursor: pointer;" οnclick="refreshCode()" id="captcha"/>
</td>
</tr>


 

 

//4.生成验证码

public function captcha(){
	$captchaTool = new CaptchaTool;
	$captchaTool->generate();
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值