您的位置:首页 > 编程语言 > PHP开发

PHP验证码显示与验证

2014-12-26 23:23 387 查看
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;" onclick="refreshCode()" id="captcha"/>
</td>
</tr>


 

 

//4.生成验证码

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


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: