session的使用
验证码小例子
创建添加session
public function login()
{
$this->load->library('session');
$user = array(
'id'=>3,
'name'=>'jack'
);
//添加session
$this->session->set_userdata('user', $user);
// 在这里获取不到刚放入的数据,只有页面重新加载后跳转到别的控制器,url中才能获取到
}
注意:在config.php中添加encryption_key。可用echo md5(uniqid());生成随机key填入
获取session(注意要在不同url中才能读到之前添加的session)
public function showsession()
{
$this->load->library('session');
//读session
$user = $this->session->userdata('user');
var_dump($user);
// 数组这么取,直接[]里面填键值
echo $user['name'].'<br>';
$test = $this->session->flashdata('test');
echo $test;
}
验证码
- controller类
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
*/
class Checkcode extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index()
{
echo "OKKK";
}
public function check()
{
echo "OKKK";
$this->load->helper('captcha');
$this->load->helper('url');
$imgArr = array(
'word' => rand(1000,9999),
'img_path'=>'./captcha/',
'img_url'=>base_url().'captcha/',
// 'img_width' => 150,
// 'img_height' => 30,
'expiration' => 7200
);
$img = create_captcha($imgArr);
// echo $img['image'];
$this->session->set_userdata('code',$img['word']);
$this->load->view('checkview',array('cap'=>$img['image']));
}
public function checkcodes()
{
$code = $this->session->userdata('code');
// echo $code;
$inputcode = $this->input->post('code');
// echo $inputcode;
$msg = '';
if($code == $inputcode){
$msg = '验证码正确';
}else{
$msg = '验证码错误';
}
$this->load->view('successview', array('msg'=>$msg));
}
}
- 验证码输入页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>验证码</title>
<link rel="stylesheet" href="">
</head>
<body>
<form action="checkcodes" method="post" accept-charset="utf-8">
<input type="text" name="code" value="" placeholder="请输入验证码"><?php echo $cap; ?>
<input type="submit" name="" value="login">
</form>
</body>
</html>
- 成功/失败页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>成功页面</title>
<link rel="stylesheet" href="">
</head>
<body>
<?php echo $msg;?>
</body>
</html>
注意:在autoload.php中,添加
$autoload['helper'] = array('url');
$autoload['libraries'] = array('session');
config.php中添加encryption_key