How to validate Session in codeigniter? - php

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');
}
...
}

Related

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.

How to redirect to url if logged in successful using codeigniter?

I am enable enable_query_strings and want to redirect url when user login successful through redirect() method.
Url look like this:
http://localhost/DemoTest/index.php?c=admin_controller&m=login&d=backend
config file setting:
$config['uri_protocol'] = 'QUERY_STRING';
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = TRUE;
admin_controller Code:
function login() {
$data['page_title'] = "Admin Login";
if (isset($_POST['username'])) {
$this->load->library('form_validation');
$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 {
$result = $this->admin_model->check_login();
if ($result) {
$user_data = array(
'username' => $_POST['username'],
'login' => TRUE,
);
$this->session->set_userdata($user_data);
site_url('m=admin_controller&t=dashboard&s=backend');
//Here i can call redirect() function to redirect this url
http://localhost/DemoSite/index.php?c=admin_controller&m=dashboard&d=backend
} else {
$this->session->set_flashdata('login_failed', 'The login info you entered is invalid');
}
}
}
$this->load->view('backend/templates/header_assets.php', $data);
$this->load->view('backend/login');
}
After a login successfully done page redirected using redirect(), see below example:
redirect('Login', 'refresh');
you just paste this line and replace login to your controller name and method

Unable to redirect url with callback in codeigniter

I just create login class that check the valid user, after that user enter in his/her home section. But now i need to change the destination of the user's home conditionally, Unable to
attach switch case in url redirection.
Note: I think varibale not properly passed in function.Plz help me
My code as Follow:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('userp','',TRUE);
}
function index($dest)
{
$this->load->view('header');
//This method will have the credentials validation
$this->load->library('form_validation');
$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() == FALSE)
{
//Field validation failed. User redirected to login page
$data['msg'] = "";
$this->load->view('login',$data);
}
$this->load->view('footer');
}
function check_database()
{
//Field validation succeeded. Validate against database
$email = $this->input->post('email');
//query the database
$password= $this->input->post('password');
$result = $this->userp->login($email,$password);
if($result!==FALSE)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' =>$row->email,
'fname' =>$row->first_name,
'lname' =>$row->last_name,
'pic'=>$row->pic
);
$this->session->set_userdata('logged_in',$sess_array);
}
switch($dest){
case 'NULL':{
redirect('home','refresh');
break;
}
case 'part1':{
redirect('subhome','refresh');
break;
}
case 'part2':{
redirect('subhome1','refresh');
break;
}
default :{
redirect('mainhome','refresh');
break;
}
}
return TRUE;
}
else
{
$data['msg'] = "Something Wrong Username/Password";
$this->load->view('login',$data);
//return false;
}
}
};
?>
The problem is that you are passing $dest to the index() function but you are attempting to use it in your check_database() function. So either you want to move your switch into the index function or you want to pass $dest to check_database() like
function check_database($dest)
{
//You can use $dest in here
}
If you want to pass an extra parameter to your callback function you need to put it in brackets like
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database[parameter]');
or
$this->form_validation->set_rules("password", "Password", "trim|required|xss_clean|callback_check_database[$parameter]");

CodeIgniter Form Validation Error Redirect

I have the following controller, which works fine in terms of validating the form and displaying the error.
The user attempts to login from: http://mydomain.com/index.php/login
However, when the user enters the wrong credentials, it loads the login view properly (as it should) and displays the error "Invalid Login" properly, but the URI in the browser window shows:
http://mydomain.com/index.php/verify_login (as opposed to the one above).
How do I redirect after the failed validation to just ".../index.php/login"
Here is the code in question:
<?
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
}
function verify_login()
{
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->index();
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}
UPDATE: Cyrode's solution fixes that issue, but now it's not displaying the "Invalid Login" error message (set_message) from the check_database() function on loading the view. Any ideas what I am doing wrong here?
UPDATE 2:
Here you go:
class Login extends CI_Controller {
public function index()
{
$this->load->helper(array('form'));
$this->load->helper('url');
$this->load->view('login_page');
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
$this->load->view('login_page');
}
else
{
//Go to private area
redirect('private_area', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->login_model->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-error">Invalid username or password</div>');
return false;
}
}
}
Just do all of your form processing in the index() method.
public function index()
{
$this->load->model('login_model','',TRUE);
$this->load->library('form_validation');
$this->load->helper('url');
$this->form_validation->set_error_delimiters('<label class="error">', '</label>');
$this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if ($this->form_validation->run() == false)
{
$this->load->view('login_page');
}
else
{
redirect('private_area', 'refresh');
}
}
Then, make sure your form's action goes to login and not verify_login.
By the way, don't xss_clean password fields, because it may change their value, and your user will be left wondering why their perfectly-typed password isn't working. You should be hashing the password, anyway, which will eliminate security issues.

unable destroy session in codeigniter

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

Categories