Cakephp中使用Captcha实现更加安全的验证码

 

Captcha官方

http://www.captcha.ru/en/

Captcha下载

http://www.captcha.ru/en/kcaptcha/

本地下载1.2.6版本

 

首先可以使用如下程序得到验证码图片,注意在程序在生成图片时就调设置了会话变量。

getImage.php

 

<?php 

include('kcaptcha.php');

session_start();

$captcha = new KCAPTCHA();

$_SESSION['captcha_keystring'] = $captcha->getKeyString();

?>

 

接下来通过如下的表单调用验证码图片,并验证用户输入是否与验证码图片值相符。

index.php

 

<?php 

session_start();

$true_key_string = $_SESSION['captcha_keystring'];

echo $true_key_string;

?>

<html>

<body>

<form action="" method="post">

<img src="getImage.php?<?php echo session_name()?>=<?php echo session_id()?>"/><br/>

<input type="text" value="" name="keystring"/>

<input type="submit" value="check" />

</form>

<?php 

if(isset($_SESSION['captcha_keystring']) && $true_key_string == $_POST['keystring'])

{

echo "Correct";

}else

{

echo "Wrong";

}

?>

</body>

</html>

 

那么,如何在Cakephp中使用Captcha呢?

首先把Kcaptcha文件夹拷贝到vendor目录。因为验证码要在很多控制器中使用,因此最好把该项功能用组件进行封装,该组件包括生成图片和验证两项功能。在controllers/components目录下新建captcha.php文件。

 

 

<?php

class CaptchaComponent extends Object {

var $Controller = null;

 

function startup(&$controller)

{

$this->Controller = $controller;

}

 

function render()

{

App::import('vendor', 'kcaptcha/kcaptcha');

$kcaptcha = new KCAPTCHA();

$this->Controller->Session->write('captcha', $kcaptcha->getKeyString());

exit;

}

 

function checkCaptcha($str)

{

if ($this->Controller->Session->check('captcha'))

{

$s_captcha = $this->Controller->Session->read('captcha');

if(!empty($str) && $str == $s_captcha)

return true;

}

}

return false;

}

}

?>

 

 

 

接下来,为了能在视图中调用验证码图片,可以在控制器(比如Users控制器)中加入Captcha组件。或者单独创建一个Captchas控制器来生成验证码图片。

 

<?php

class CaptchasController extends AppController {

 

var $name = 'Captchas';

var $uses = array();

var $components  = array('Captcha');

var $helps = array('Cache');

var $cacheAction = true;

 

function index() {

Configure::write('debug', '0');

$this->autoRender = false;

$this->Captcha->render();

}

}

?>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值