unable destroy session in codeigniter - php

What I want to implement is a simple login page, if user login successfully, then redirect to main page, else remain login page.
I have 1 controller named login, and 1 model named main.
When user click the login button, the login/login_send will be called.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('model_login');
}
function index()
{
if ($this->model_login->is_logged_in())
{
redirect('main');
}
else
{
// load login page
$data['main'] = 'view_login';
$data['style'] = 'style_login';
$this->load->view('template', $data);
}
}
function login_send()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
if ( $this->model_login->validate_user() )
{
$user_session_data = array(
'username' => $this->input->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata($user_session_data);
redirect('main');
}
else
{
redirect('login');
}
}
}// end function login_send
function logout()
{
if ($this->model_login->is_logged_in())
{
$this->session->sess_destroy();
$this->session->set_userdata(array('username' => '', 'is_logged_in' => 0));
log_message('debug', 'Some variable was correctly set');
}
redirect('login','refresh');
}
}// end class Login
?>
Model_login here is just to help to verify if user is logged in, by check the session data.
<?php
class Model_login extends CI_MOdel{
function _isUserExist($username, $password)
{
$options = array(
'UserName' => $username,
'Password' => $password
);
$query = $this->db->get_where('userinfo', $options);
return $query->num_rows() > 0;
}
function validate_user()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
return ($this->_isUserExist($username, $password));
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if ( !isset($is_logged_in) || $is_logged_in != 1 ) return FALSE;
else return TRUE;
}
}// end class model_login
?>
When first time login, and then logout, there is no problem. However, if I login second time, I can not log out. Even the login/logout was called correctly, I also refreshed the page, but the session['is_logged_in'] == 1. Something wrong with my code?

In your application/config/config.php try changing
$config['sess_time_to_update'] = 300; //This is the default setting in ver 2.1.1
to
$config['sess_time_to_update'] = 0;
This gave me some problems a few years back

Related

PHP login using Ion Auth and Facebook login works locally on MAMP but not Web Server

The problem I'm facing is that manual new user subscription works locally but does not work on remote web server. The only difference between the non-working one and the one that works is that I upgraded Ion Auth to version 2 and added Facebook-Ion Auth library for Facebook Login.
Again, it works perfect locally, but not on the web server. PHP versions have been tested and work fine.
Here's the controller it gets stuck on (shows a blank page or goes back to homepage).
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Signup extends CI_Controller {
function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->load->library('form_validation');
$this->load->helper('url');
$this->load->library('forms/signupform');
$this->form_validation->set_error_delimiters(
$this->config->item('error_start_delimiter', 'ion_auth'),
$this->config->item('error_end_delimiter', 'ion_auth')
);
}
/**
* #signup page of freelancer
*/
public function index()
{
$data['title'] = lang('title_registration');
$data['bodyclass'] = 'hold-transition register-page';
$data['js_bottom_files'] = array('plugins/iCheck/icheck.min', 'js/custom');
$data['cssfiles'] = array('plugins/iCheck/square/blue');
// POST SIGNUP FORM
if ('POST' == $this->input->server('REQUEST_METHOD') && $this->input->post('registersubmit') ) {
// Signup Action
$data['message_success'] = $this->signup();
}
// $user['checked'] = '';
// if ($this->input->post('agree') == 'yes') {
// $user['checked'] = 'checked';
// }
$data['form'] = $this->signupform->view($user);
//Render Or redirect according to User AccessLevel
if (!$this->ion_auth->logged_in()) {
$this->template->load('layout', 'home', $data);
} elseif ($this->ion_auth->is_admin()) {
redirect(site_url('admin/dashboard'), 'refresh');
} elseif ($this->ion_auth->is_members()) {
redirect(site_url('note/create'), 'refresh');
}
}
/**
* #Signup action for user
*/
public function signup()
{
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
// $this->form_validation->set_rules('full_name', lang('label_full_name'), 'required');
$this->form_validation->set_rules('loginPassword', lang('label_signup_createpassword'), 'required|min_length['.$this->config->item('min_password_length', 'ion_auth').']|max_length['.$this->config->item('max_password_length', 'ion_auth').']');
// $this->form_validation->set_rules('confirmpassword', lang('label_signup_confirmpassword'), 'required');
// $this->form_validation->set_rules('agree', 'Agree', 'required');
if ($this->form_validation->run() == true) {
$email = $this->input->post('email');
$password = $this->input->post('loginPassword');
// $additional_data = array('first_name' => $this->input->post('full_name'), 'school' => $this->input->post('school_name'));
$group_ids = array( 'user_groups' => 2);
if ($this->ion_auth->register($email, $password, $email, $additional_data, $group_ids)) {
//check to see if we are creating the user
//$this->session->set_flashdata('message_success', $this->ion_auth->messages());
//redirect(site_url('/'), 'refresh');
if($this->ion_auth->login($email, $password)){
redirect(site_url('note/create'), 'refresh');
}
} else {
$this->session->set_flashdata('message_error', $this->ion_auth->errors());
redirect(site_url('/'), 'refresh');
}
}
}
}
/* End of file signup.php */
Potentially not the issue without more information but:
$group_ids = array( 'user_groups' => 2); should just be $group_ids = array('2')
See usage of the register function here.
and in the Ion auth config file $config['identity'] should be set as email (if you haven't done so already).

Cannot redirect to login page if user not authenticated using constructor

I have an Admin controller which handles the user login and other admin functionality like managing a basic cms. In the constructor I check if the users session present which is set once they login. If not and they try to access a restricted page, they should be redirected. If I redirect to another page then when going to the login page I get redirected right away as obviously that check is done in the constructor, but as soon as I try to redirect to the login page I get an error:
This page isn’t working localhost redirected you too many times. Try
clearing your cookies. ERR_TOO_MANY_REDIRECTS
class Admin extends Controller {
public function __construct()
{
if(!isLoggedIn()) {
redirect('admin/login');
}
$this->AuthModel = $this->model('Auth');
}
isLoggedIn is a function:
function isLoggedIn() {
if(isset($_SESSION['user_id']) && isset($_SESSION['browser']) && $_SESSION['browser'] == $_SERVER['HTTP_USER_AGENT']) {
return true;
} else {
return false;
}
}
Login method:
public function login()
{
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = trim($_POST['password']);
$data = [
'email' => $email,
'password' => $password,
'email_error' => '',
'pass_error' => '',
'no_user' => '',
'pass_wrong' => ''
];
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$data['email_error'] = 'Invalid email address <br />';
}
if(empty(trim($_POST['password']))) {
$data['pass_error'] = 'Password required';
}
if(!empty(trim($_POST['email'])) && !$this->AuthModel->getUserByEmail($email)) {
$data['no_user'] = 'Email does not exist';
}
if(!empty($data['email_error']) || !empty($data['pass_error']) || !empty($data['no_user'])) {
$this->view('admin/login', $data);
} else {
$loggedInUser = $this->AuthModel->login($email, $password);
if($loggedInUser) {
$this->CreateUserSession($loggedInUser);
} else {
$data['pass_wrong'] = 'Incorrect login details';
$this->view('admin/login', $data);
}
}
} else {
$data = [
'email' => '',
'password' => '',
'email_error' => '',
'pass_error' => '',
'no_user' =>'',
'pass_wrong' => ''
];
$this->view('admin/login', $data);
}
}
You are using same controller for login and other functionalities. Every time it checks for authentication and it gets no. And it loops over again. try to implement your login functionalities in a separate Controller.

I get error when i login to my project and then go back to the base url

I'm getting error when login to my project and then goto the base url. The below is the error which i get
My Login page [ see the url ]
After logging in , if i remove the highlighted segments[pls see below image] after which i get the above error
I know these error are due to headers so can somebody help me in saying what error am i making in header. An also say how to make good use of session so that the form is to resubmitted when i refresh after logging in. Below are the header codes.
login header
<?php if(isset($this->session->userdata['logged'])){
header("location: http://localhost/capacity_planner/login/login_check");
}
?>
admin dashboard[after logging in header]
<?php if(isset($this->session->userdata['logged'])){
$email = ($this->session->userdata['logged']['email']);
}else{
header("location: http://localhost/capacity_planner/login");
}
?>
controller side
public function login_check(){
$data['base_url'] = base_url();
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run($this) == false) {
$this->index();
} else {
if(isset($this->session->userdata['logged'])) {
$data['login_bg'] = $this->input->post('login_bg');
$this->load->view("admin_db", $data);
}
}
function check_database($password){
$email= $this->input->post('email');
$user = $this->user->loginCheck($email, $password);
if($user[1] == 1){
$result = $this->user->user_details($email);
if($result != false) {
$session_data = array(
'id' => $result[0]->id,
'email' => $result[0]->cp_email,
);
$this->session->set_userdata('logged', $session_data);
return true;
}
} else{
$this->form_validation->set_message('check_database', $user[0]);
return false;
}
}
ERR_TOO_MANY_REDIRECTS is caused when strucked up in a conditional loop
I assume you want to redirect to admin dashboard if you go to index after logged in..
Try adding these lines in your public function index()
public function index(){
if(isset($this->session->userdata['logged'])) {
//admin_db display function eg.redirect('admindashboard');
}
else{
//load your index view
this->load->view('your_index_view');
}
}
or you can check reverse way in admin dashboard function like this
public function dashboard(){
if($this->session->userdata('logged') == ''){
redirect('index');
}
else{
$this->load->view('dashboard view');
}
}
This is my assumption.Kindly check it.

CodeIgniter: 404 Page Not Found ( In Hosting Server )

note : everything going well when I try in Localhost.
So I have a problem when I want to call my do_login controller in my login form.
this is my controller :
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Do_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('login_model', '', TRUE);
}
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email', 'trim|required');
$this->form_validation->set_rules('password', 'password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login_view');
}
else
{
redirect('home', 'refresh');
}
}
public function check_database($password)
{
$email = $this->input->post('email', TRUE);
$result = $this->login_model->check_login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'user_id' => $row->user_id,
'email' => $row->email
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Email / Password salah');
return FALSE;
}
}
}
?>
this is my view :
<?php
$attributes = array('class' => 'form-signin', 'id' => 'myform');
echo form_open('do_login', $attributes);
?>
When I try it in Localhost, everything going well and smooth.
But when I try in my web server, everytime I submit the login form, I directed into 404.
Thanks for your help :)
Check your file names Because it happens with me that different case file name was worked on localhost but not on server.
So check it once.

How to validate Session in codeigniter?

I am trying to create a session in Codeigniter. I have loaded session and encrypt library in autoload. By default the login.php page opens. I want to open the dashboard.php page, if the user is already logged in. I have written the following code, but it opens the login.php page, even after login.
Kindly tell me how to check if the session is already set or not.
public function index()
{
$data['products_data']= $this->products_model->all_products();
// $this->load->view('login');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run()== false)
{
$this->load->view('login');
}
else
{
if ($this->session->userdata('login_status')) {
$this->load->view('header');
$this->load->view('dashboard');
$this->load->view('footer');
}
else
{
$username= $this->input->post('username');
$password= $this->input->post('password');
if( $this->products_model->login_model($username,$password))
{
$sess_data= array(
'username'=> $username,
'login_status'=>'1'
);
$session_data = $this->session->set_userdata($sess_data);
$this->load->view('header');
$this->load->view('dashboard');
$this->load->view('footer');
}
}
}
}
$sessdata = $this->session->set_userdata($session_data);
if (isset($sessdata))
{
//session exists
}
else{
// no session value
}
So Your controller should look like below to avoid redirecting to login page on page refresh,
function index() {
if ($this->session->userdata('login_status')) {
//write your code for redirect to dashboard
} else {
$data['products_data'] = $this->products_model->all_products();
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('login');
} else {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->products_model->login_model($username, $password)) {
$sess_data = array(
'username' => $username,
'login_status' => '1'
);
$session_data = $this->session->set_userdata($sess_data);
//write your code for redirect to dashboard
}
}
}
}
Remove the single qoutes on
$this->session->set_userdata('$sess_data');
it is treating the variable $sess_data as a regular string.
must be:
$this->session->set_userdata($sess_data);
I rather like to create another controller for dashboard and redirect it to there after successful login. It is clean and you can do further changes easily
if( $this->products_model->login_model($username,$password))
{
$sess_data= array(
'username'=> $username
);
$session_data = $this->session->set_userdata($sess_data);
if(isset($session_data))
redirect(site_url('/dashboard/'));
}
FM: $sess_data should not be in single quotes
I will use session to record login status.
$session_data= array(
'username'=> $username,
'lgoin_status' => 1
);
$this->session->set_userdata('$session_data');
And I will check session's login_status
if ($this->session->userdata('login_status')) {
// do something
}
Edit
On your code, you should check session at first, so..
public function index()
{
if ($this->session->userdata('login_status'))
{
// do something
}
else
{
$data['products_data']= $this->products_model->all_products();
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run()== false)
{
$this->load->view('login');
}
...
}

Categories