PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 1, 2022

[FIXED] Creating session with Codeigniter 3

 January 01, 2022     codeigniter, php     No comments   

Issue

How I can set a session using a username if the login is successful? Also how to clear the session when the user is logged out. Thanks

It is a mine do login function. The log in is working fine and the database as well. I know it is not good code but I am just starting using PHP in Codeigniter 3.

    enter code here
public function dologin(){
$this->load->helper('url');
$this->load->model('user_model');
$username = $this->input->post("username");
$pass = $this->input->post("password");

$result = $this->user_model->checkLogin($username, $pass);
if ($result == 1) {
  redirect('messages/index');
} else {
  redirect('user/login');
}

}

It is my database check log in if the user and password exist.

  enter code here
  public function checkLogin($username, $pass){
    $hash =sha1($pass);
    $this->db->from('Users');
    $this->db->where('username', $username);
    $this->db->where('password', $hash);

    $query=$this->db->get();
    
    if($query->num_rows() == 1){
        return true;
    }else{
        return false;
    }

}

Solution

    $result = $this->user_model->checkLogin($username, $pass);
// if data found in your database, then
    if ($result == 1) {
       $data = array(
            'user_id' => $result[0]['id'],
            'username' => $result[0]['username'],
            'is_logged_in' => true,
        );
        $this->session->set_userdata($data);
//your session has been created
    }    

to view your session

print_r($this->session->userdata());

to logout or unset

$this->session->unset_userdata('user_id') == 'youruser_id');


Answered By - Syed Muhammad Shakayb Athar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing