search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to implement cookie login in CI framework, detailed explanation of cookie in CI framework_PHP tutorial

The example in this article describes how CI framework implements cookie login. Share it with everyone for your reference, the details are as follows:

Step one: login.php

//登陆方法
 public function login(){
  //如果用户名和密码为空,则返回登陆页面
  if(empty($_POST['username']) || empty($_POST['password'])){
   $data['verifycode'] = rand(1000,9999);//生成一个四位数字的验证码
   //将验证码放入session中,注意:参数是数组的格式
   $this->session->set_userdata($data);
   //注意:CI框架默认模板引擎解析的模板文件中变量不需要$符号
   //$this->parser->parse("admin/login",$data);
   //smarty模板变量赋值
   $this->tp->assign("verifycode",$data['verifycode']);
   //ci框架在模板文件中使用原生态的PHP语法输出数据
   //$this->load->view('login',$data);//登陆页面,注意:参数2需要以数组的形式出现
   //显示smarty模板引擎设定的模板文件
   $this->tp->display("admin/login.php");
  }else{
   $username = isset($_POST['username'])&&!empty($_POST['username'])?trim($_POST['username']):'';//用户名
   $password = isset($_POST['password'])&&!empty($_POST['password'])?trim($_POST['password']):'';//密码
   $verifycode = isset($_POST['verifycode'])&&!empty($_POST['verifycode'])?trim($_POST['verifycode']):'';//验证码
   //做验证码的校验
   if($verifycode == $this->session->userdata('verifycode')){
    //根据用户名及密码获取用户信息,注意:参数2是加密的密码
    $user_info=$this->user_model->check_user_login($username,md5($password));
    if($user_info['user_id'] > 0){
     //将用户id、username、password放入cookie中
     //第一种设置cookie的方式:采用php原生态的方法设置的cookie的值
     //setcookie("user_id",$user_info['user_id'],86500);
     //setcookie("username",$user_info['username'],86500);
     //setcookie("password",$user_info['password'],86500);
     //echo $_COOKIE['username'];
     //第二种设置cookie的方式:通过CI框架的input类库
     $this->input->set_cookie("username",$user_info['username'],3600);
     $this->input->set_cookie("password",$user_info['password'],3600);
     $this->input->set_cookie("user_id",$user_info['user_id'],3600);
     //echo $this->input->cookie("password");//适用于控制器
     //echo $this->input->cookie("username");//适用于控制器
     //echo $_COOKIE['username'];//在模型类中可以通过这种方式获取cookie值
     //echo $_COOKIE['password'];//在模型类中可以通过这种方式获取cookie值
     //第三种设置cookie的方式:通过CI框架的cookie_helper.php函数库文件
     //这种方式不是很灵验,建议大家采取第二种方式即可
     //set_cookie("username",$user_info['username'],3600);
     //echo get_cookie("username");
     //session登陆时使用:将用户名和用户id存入session中
     //$data['username']=$user_info['username'];
     //$data['user_id']=$user_info['user_id'];
     //$this->session->set_userdata($data);
     //跳转到指定页面
     //注意:site_url()与base_url()的区别,前者带index.php,后者不带index.php
     header("location:".site_url("index/index"));
    }
   }else{
    //跳转到登陆页面
    header("location:".site_url("common/login"));
   }
  }
 }
}

Step 2: User_model.php

//cookie登陆:检测用户是否登陆,如果cookie值失效,则返回false,如果cookie值未失效,则根据cookie中的用户名和密码从数据库中获取用户信息,如果能获取到用户信息,则返回查询到的用户信息,如果没有查询到用户信息,则返回0
 public function is_login(){
  //获取cookie中的值
  if(empty($_COOKIE['username']) || empty($_COOKIE['password'])){
   $user_info = false;
  }else{
   $user_info=$this->check_user_login($_COOKIE['username'],$_COOKIE['password']);
  }
  return $user_info;
 }
 //根据用户名及加密密码从数据库中获取用户信息,如果能获取到,则返回获取到的用户信息,否则返回false,注意:密码为加密密码
 public function check_user_login($username,$password){
  //这里大家要注意:$password为md5加密后的密码
  //$this->db->query("select * from ");
  //快捷查询类的使用:能为我们提供快速获取数据的方法
  //此数组为查询条件
  //注意:关联数组
  $arr=array(
   'username'=>$username,//用户名
   'password'=>$password,//加密密码
   'status'=>1   //账户为开启状态
  );
  //在database.php文件中已经设置了数据表的前缀,所以此时数据表无需带前缀
  $query = $this->db->get_where("users",$arr);
  //返回二维数组
  //$data=$query->result_array();
  //返回一维数组
  $user_info=$query->row_array();
  if(!empty($user_info)){
   return $user_info;
  }else{
   return false;
  }
}

Step 3: Other controllers:

public function __construct(){
  //调用父类的构造函数
  parent::__construct();
  $this->load->library('tp'); //smarty模板解析类
  $this->load->helper('url'); //url函数库文件
  $this->load->model("user_model");//User_model模型类实例化对象
  $this->cur_user=$this->user_model->is_login();
  if($this->cur_user === false){
   header("location:".site_url("common/login"));
  }else{
   //如果已经登陆,则重新设置cookie的有效期
   $this->input->set_cookie("username",$this->cur_user['username'],3600);
   $this->input->set_cookie("password",$this->cur_user['password'],3600);
   $this->input->set_cookie("user_id",$this->cur_user['user_id'],3600);
  }
  $this->load->library('pagination');//分页类库
  $this->load->model("role_model");//member_model模型类
  $this->load->model("operation_model");//引用operation_model模型
  $this->load->model("object_model");//引用object_model模型
  $this->load->model("permission_model");//引用permission_model模型
}

Readers who are interested in more CodeIgniter related content can check out the special topics of this site: "codeigniter introductory tutorial", "CI (CodeIgniter) framework advanced tutorial", "php excellent development framework summary", "ThinkPHP introductory tutorial", "Summary of Common Methods in ThinkPHP", "Introduction Tutorial on Zend FrameWork Framework", "Introduction Tutorial on PHP Object-Oriented Programming", "Introduction Tutorial on PHP MySQL Database Operation" and "Summary of Common PHP Database Operation Skills"

I hope this article will be helpful to everyone’s PHP program design based on the CodeIgniter framework.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1127858.htmlTechArticleDetailed explanation of the method of cookie login in CI framework, detailed explanation of cookie login in ci framework. This article describes the method of cookie login in CI framework. . Share it with everyone for your reference, the details are as follows: The first step...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor