Codeigniter基础2

2 篇文章 0 订阅

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

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

<?php

defined('BASEPATH')OR exit('NO direct script access alloed');

class Welcome extends CI_Controller{

     public function index(){

           $out_datas=$this ->_captcha();

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


}

     private function _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");//加载验证码
最后显示


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值