好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Codeigniter入门 (2) 验证码

简单的验证码,基本在登录时都用到,先使用CI自带的captcha方法,位于system/helpers/captcha_helper.php

控制器

   首先,在控制器中加载captcha_helper.php辅助方法,代码如下

 

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

  

classWelcomeextendsCI_Controller {

      

    publicfunctionindex()

    {

        $out_datas=$this->_captcha();

        $this->load->view('welcome_message',$out_datas);

    }

    privatefunction_captcha(){

        $this->load->helper("my_captcha");//加载验证码

        $vals = array(

              'img_path'    =>'./captcha/',       //验证码图片存放的地址

              'img_url' => base_url()."/captcha/", //图片访问的路径

              'img_width'   =>'60',               //图片的宽度

              'img_height'=>20,                   //高度

              'expiration'=>1,                    //存放时间,1分钟

              'word_length'=>4                     //显示几位验证数字

        );

        $cap = create_captcha($vals);

        $out_datas["v_img"]=$cap["image"];               //生成的图片文件

        $out_datas["v_word"]=$cap["word"];               //生成的验证码,也可放入session中管理

        return$out_datas;

    }

}

 #在'img_path'    =>'./captcha/',  我们将生成的图片存放在 项目/captcha目录下,所以我们要在application的同级目录中创建captcha目录,用来存放验证码图片applicationcaptcha --在application 的同级目录创建文件system

视图

   然后在application/views/welcome_message.php中显示图片

 

<div id="container">

    <h1>Welcome to CodeIgniter!</h1>

  

    <div id="body">

        <?=form_open("welcome/login")?>

          <p>验证码 :  <input type="text"name="rand"style="width: 50px;"maxlength="4"/>

          <?=$v_img?>

          </p>

          <input type="hidden"name="word"value="<?=$v_word?>"/>

          <input type="submit"value="验证"/>

        </form>

    </div>

  

     <pclass="footer">Page renderedin<strong>0.4593</strong> seconds. <?php echo  (ENVIR'development') ? 'CodeIgniter Version <strong>'. CI_VERSION .'</strong>':''?></p>

</div>

 

   在这里使用到了form_open方法,所以需要加载form_helper.php文件,不过,这个方法以后会经常用到,所以加在application/config/autoload.php文件中加载,这样CI就会自动帮我们加载。

 

1

$autoload['helper'] = array('url','form');

显示如下

5.png

 

#由于我们设定的image宽度为60px,同时只显示4个字符,而CI中默认为150px,长度为8,所以刷新时,验证码会跳到图片之外,修改办法如下.

1、将字体颜色修改成黑体,这样好看清楚

2、验证码在图片中显示(不跳出图片)

 

首先

  在application/helper/中创建   MY_captcha_helper.php 文件,内容与system/helper/captcha_helper.php中一致.然后修改其中的代码。

 

 

-- 在第88行

//$text_color   = imagecolorallocate($im, 204, 153, 153);

  $text_color   = imagecolorallocate ($im,0,0,0);//字体为黑色

    

-- 在128行

  //$x = rand(0, $img_width / ($length / 3));

  $x = rand(0, $img_width/($length));//X坐标

    

-- 在143行

  //$y = rand(0 , $img_height / 2);

    $y = rand(0, $img_height/3);//Y坐标

my_captcha_helper.php 下载

然后

  修改控制器中的加载代码

 

$this->load->helper("my_captcha");//加载验证码

最后显示

查看更多关于Codeigniter入门 (2) 验证码的详细内容...

  阅读:75次