Captcha官方
Captcha下载
http://www.captcha.ru/en/kcaptcha/
使用Captcha可以实现安全的验证码功能,Captcha提供了多种风格和样式的风格比如
使用方法超级简单
getImage.php
1.
<?php
2.
session_start();
3.
include ( 'kcaptcha.php' );
4.
$captcha = new KCAPTCHA();
5.
?>
index.php
1.
<html>
2.
<body>
3.
<img src= "getImage.php" />
4.
</body>
5.
</html>
Captcha会自动在Session中设置一个值来保存已经生成的验证码,要判断验证码是否正确,可以这样做:
1.
//Captche会自动在Session中存储一个名为captcha_keystring的字符串
2.
//只要验证一下提交的验证码是否和它相等就OK了
3.
4.
if (isset($_SESSION[ 'captcha_keystring' ]) && $_SESSION[ 'captcha_keystring' ] == $_POST[ 'keystring' ]){
5.
echo "Correct" ;
6.
} else {
7.
echo "Wrong" ;
8.
}
那么,如何在Cakephp中使用Captcha呢?
介绍一下, Yoophi 在Cakephp通过组件方式使用Captcha的方法
将kcaptcha文件夹拷贝到vendors目录
在components中写一个新的组件
代码如下:
01.
<?php
02.
class CaptchaComponent extends Object {
03.
var $Controller = null;
04.
05.
function startup(& $controller )
06.
{
07.
$this ->Controller = $controller ;
08.
}
09.
10.
function render()
11.
{
12.
App::import( 'vendor' , 'kcaptcha/kcaptcha' );
13.
$kcaptcha = new KCAPTCHA();
14.
$this ->Controller->Session->write( 'captcha' , $kcaptcha ->getKeyString());
15.
exit ;
16.
}
17.
18.
}
19.
?>
然后,写一个生成验证码的方法,比如
01.
class UsersController extends AppController {
02.
03.
var $name = 'Users' ;
04.
var $components = array ( 'Captcha' );
05.
06.
function captcha() {
07.
Configure::write( 'debug' , '0' );
08.
$this ->autoRender = false;
09.
$this ->Captcha->render();
10.
}
11.
12.
}
视图中的调用
1.
echo $html ->image( array ( 'controller' => 'Users' , 'action' => 'captcha' ));
验证提交的验证码是否正确
01.
function _checkCaptcha( $model ) {
02.
if ( $this ->Session->check( 'captcha' )) {
03.
$s_captcha = $this ->Session->read( 'captcha' );
04.
05.
if (! empty ( $this ->data[ $model ][ 'captcha' ]) && $this ->data[ $model ][ 'captcha' ] == $s_captcha ) {
06.
return true;
07.
}
08.
}
09.
10.
return false;
11.
}
总结
Captcha是一个免费的验证码文件,使用方法超级简单,但是安全性很高,配置方法简单,可以应用于多种开发程序框架
Captcha的配置文件为kcaptcha_config.php
通过它可以变更生成的图片大小,样式等内容,有兴趣的话自己可以看看!
本文介绍Captcha验证码的安装及在CakePHP中的集成方法。Captcha提供多样化的验证码风格,配置简便,安全性高。文中详细讲解了从下载、安装到在项目中使用的全过程。
3379





