Codeigniter userdata removed right after creation - php

I am working on a login script and it used to work perfectly but then all of a sudden it stopped working. I commented out a lot of code but it still does the same. When I login it sees the userdata but it disappears right after.
This is what I got in my controller: (I leave commented code out)
Login controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller {
public function __construct(){
parent::__construct();
$this->smarty->assign('header',"../../../views/login_header.tpl");
$this->smarty->assign('footer',"../../../views/login_footer.tpl");
$this->load->library('form_validation');
}
public function index()
{
$this->load->model('mdl_login');
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|callback_credential_check');
if ($this->form_validation->run() == FALSE)
{
$errors = validation_errors();
$this->smarty->assign('errors', $errors);
}
elseif($this->mdl_login->login($email, $password) == FALSE){
$errors = 'Your login information is incorrect.';
$this->smarty->assign('errors', $errors);
}
else //Validation success
{
//Get user
$user = $this->mdl_login->user($email);
$user['logged_in'] = TRUE;
//It's not the if statement here because I also tried without it
if($this->session->userdata('logged_in') == FALSE){
$this->session->set_userdata($user);
}
print_r($this->session->all_userdata());
die(); //At this point the userdata is correct but on refresh or going to another page it isn't
//Redirect to homepage
//redirect('dashboard', 'refresh');
}
$this->smarty->view('login/login.tpl');
}
}
Login Model:
<?php
class Mdl_login extends CI_Model {
public function login($email, $password){
return TRUE;
}
public function user($email){
$query = $this->db->get_where('korisnici_tbl', array('email' => $email));
return $query->row_array();
}
}
?>
My_Controller:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/* load the MX_Controller class */
require APPPATH."third_party/MX/Controller.php";
class MY_Controller extends MX_Controller {
public function __construct(){
print_r($this->session->all_userdata());
$this->smarty->assign('header',"../../../views/header.tpl");
$this->smarty->assign('footer',"../../../views/footer.tpl");
$this->smarty->assign('form_url_plugin',"../../../views/form_url_plugin.tpl");
$this->smarty->assign('controller',$this->uri->segment(1));
$this->smarty->assign('userdata',$this->session->all_userdata());
if($this->session->userdata('logged_in') != TRUE && $this->uri->segment(1) != 'login'){
if($this->session->userdata('logged_in') != TRUE){
print_r($this->session->all_userdata());
}
//redirect('login', 'refresh');
}
}
}
I am using modular extensions. I am sure there is nothing wrong in My_Controller because I tested it by setting it back to MX_Controller. (I never changed anything in MX_Controller)

I found the answer to my question. In my model I was adding all data of the logged in user. One of the columns contain the IP Address. And I don't know why exactly but when I add the IP Address to the session it removes the session, and adds a new session with the default codeigniter session data and a new session id.
So somehow I can't store IP Addresses in my userdata.

Related

Cant login with email and username that is on database (Codeigniter php)

i already have database with table of username, email (primary key), and password and have already filled them. but when i try to put those emails and password on my web page, it is read as wrong.
Here is my login controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login_controller extends CI_Controller {
public function __construct() {
parent::__construct();
//load the required libraries and helpers for login
$this->load->helper('url');
$this->load->library(['form_validation','session']);
$this->load->database();
//load the Login Model
$this->load->model('LoginModel', 'Login_controller');
}
public function index() {
//check if the user is already logged in
$logged_in = $this->session->userdata('logged_in');
if($logged_in){
//if yes redirect to welcome page
redirect(base_url().'HomeLoggedIn_controller/index/');
}
//if not load the login page
$this->load->view('login/v_login');
}
public function doLogin() {
//get the input fields from login form
$email = $this->input->post('email');
$password = sha1($this->input->post('password'));
//send the email pass to query if the user is present or not
$check_login = $this->Login_controller->checkLogin($email, $password);
//if the result is query result is 1 then valid user
if ($check_login) {
//if yes then set the session 'loggin_in' as true
$this->session->set_userdata('logged_in', true);
redirect(base_url().'HomeLoggedIn_controller/index/');
} else {
//if no then set the session 'logged_in' as false
$this->session->set_userdata('logged_in', false);
//and redirect to login page with flashdata invalid msg
//$this->session->set_flashdata('msg', 'Username / Password Invalid');
redirect(base_url().'Login_controller/index/');
}
}
public function logout() {
//unset the logged_in session and redirect to login page
$this->session->unset_userdata('logged_in');
redirect(base_url().'Login_controller/index/');
}
}
login model:
<?php
class LoginModel extends CI_Model
{
public function checkLogin($email, $password) {
//query the table 'users' and get the result count
$this->db->where('email', $email);
$this->db->where('password', $password);
$query = $this->db->get('tb_user');
return $query->num_rows();
}
}
i try the controller and model from a website and i've already change certain things on my view page to sync it with the controller.
Hello if I may get you right you want to verify the login detail from your model. Please use this in your controller. I hope this will help you solve you issue.
defined('BASEPATH') OR exit('No direct script access allowed');
class Login_controller extends CI_Controller {
public function __construct() {
parent::__construct();
//load the required libraries and helpers for login
$this->load->helper('url');
$this->load->library(['form_validation','session']);
$this->load->database();
//load the Login Model
$this->load->model('LoginModel', 'Login_controller');
}
public function index() {
//check if the user is already logged in
$logged_in = $this->session->userdata('logged_in');
if($logged_in){
//if yes redirect to welcome page
redirect(base_url().'HomeLoggedIn_controller/index/');
}
//if not load the login page
$this->load->view('login/v_login');
}
public function doLogin() {
//get the input fields from login form
$email = $this->input->post('email');
$password = sha1($this->input->post('password'));
//send the email pass to query if the user is present or not
$check_login = $this->LoginModel->checkLogin($email, $password);
//if the result is query result is 1 then valid user
if ($check_login) {
//if yes then set the session 'loggin_in' as true
$this->session->set_userdata('logged_in', true);
redirect(base_url().'HomeLoggedIn_controller/index/');
} else {
//if no then set the session 'logged_in' as false
$this->session->set_userdata('logged_in', false);
//and redirect to login page with flashdata invalid msg
//$this->session->set_flashdata('msg', 'Username / Password Invalid');
redirect(base_url().'Login_controller/index/');
}
}
public function logout() {
//unset the logged_in session and redirect to login page
$this->session->unset_userdata('logged_in');
redirect(base_url().'Login_controller/index/');
}
}
Error discovered! you did not load the model method checklogin well
You used $this->Login_controller->checkLogin($email, $password); instead of $this->LoginModel->checkLogin($email, $password);. Which result to your error. Please replace your code with mine.
I hope this helped you if not call my attention, okay
Try changing
$check_login = $this->Login_controller->checkLogin($email, $password);
To:
$check_login = $this->checkLogin($email, $password);

CodeIgniter is not redirecting properly

I'm trying to implement basic section that only a logged-in user can access. I overrided CI_Controller, as follow:
//file created in application/core/MY_Controller.php
class Auth_Controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('session');
if ($this->session->userdata('user_logged') !== null){
redirect(base_url() . 'dashboard');
die();
} else {
redirect(base_url() . 'auth/login');
die();
}
}
And then I extend from Auth_Controller all the other controllers that are only available for the logged-in user, as follow:
class Dashboard extends Auth_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('dashboardView');
}
}
But after the login is successful, it doesn't redirect to dashboardView.
Anyone knows what is really happening?
You are redirecting infinitely to the Dashboard controller in this part of the code:
if ($this->session->userdata('user_logged') !== null){
redirect(base_url() . 'dashboard');
die();
}
Use this instead (redirect to the login form if the user is not logged in):
class Auth_controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->library('session');
// If the user is not logged in
if ($this->session->userdata('user_logged') === null){
// Redirect to http://yoursite/auth/login
// No need for the base_url function, redirect does it for you
redirect('auth/login');
// You don't have to exit/die, redirect() already does that
}
}
}
Opinions
If I check the null, will use like this != null. BUT in CI its a best option to check empty() rather null.
If I use redirect() will use it like this redirect('dashboard');
Code will be
if (!empty($this->session->userdata('user_logged'))) {
redirect('dashboard');
else {
redirect('auth/login');
}
Make sure your site will load without index.php in URL. If no search for .htaccess to your site.

Login with Ajax in Codeigniter (Controllers and Models can not execute Query Database)

I have a View that will send Login data with Ajax jquery as follows :
views/Login.php
I have a View that will send Login data with Ajax jquery as follows :
views/login.php
<!-- begin snippet: js hide: false console: true babel: false -->
That will send username & password to Model Login / insert_login
controller/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct ()
{
parent::__construct();
$this->load->model('Login_Model');
}
public function index ()
{
$this->load->view('Login');
}
public function insert_login ()
{
$user = $this->input->post('user');
$pass = $this->input->post('pass');
$cekUser = $this->Login_Model->check_user($user);
if (empty($cekUser->username)) {
$sts = 'user_wrong';
}else{
if (md5($pass) != $cekUser->password) {
$sts = 'pass_wrong';
}else{
if ($cekUser->tipe_user == 'admin'){
$sts = 'success_admin';
$this->session->set_userdata(array('user'=>$user,'status'=>'admin'));
redirect(base_url('Admin/Home'));
}else{
$sts = 'success_user';
$this->session->set_userdata(array('user'=>$user,'status'=>'user'));
redirect(base_url('Admin/Home'));
}
}
}
echo '{"status":"'.$user.'"}';
}
public function logout ()
{
$this->session->sess_destroy();
redirect(base_url('Admin/Login'));
}
}
?>
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login_Model extends CI_Model {
public function check_user ($user)
{
return $this->db->get_where('m_user', array('username' => $user))->row();
}
}
?>
I wonder why Query Database Function get_where / query / Any query can not be executed, but I have added Liblary Database in autoload.php:
$autoload['libraries'] = array('database','session'),
And I test using a Controller other than Login Controller still can run.
Why only in the model & Login controller can not execute Query?
But if I try to display the data captured divariabel:
$user = $this->input->post('user');
$pass = $this->input->post('pass');
echo $user.' '.pass;
When i test like it can already get and display data, tapi masalahnya kenapa ketika memunculkan Query tidak muncul apapun.
Please help me, I've really stack, stay up every day to clean up my job ...
set data into array in controller file
set name of array key as your database field name username & password
controller file
$user = $this->input->post('user');
$pass = $this->input->post('pass');
$where=array('username'=>$user,
'password'=>md5($pass));
$cekUser = $this->Login_Model->check_user($where);
give yout table name in from query
model file
class Login_Model extends CI_Model {
public function check_user ($where)
{
$this->db->select('*');
$this->db->from('table_name');
$this->db->where($where);
$res=$this->db->get();
return $res->result();
}
}

CodeIgniter session lost after redirect

I have a project that use CI 3 I developed on localhost in Windows using XAMPP, and final product was deployed on Debian Apache server. I tried to logged in but it's redirected back to default controller.
I tried to enter the wrong login and it's show the error correctly, but when I entered the right login it keeps comeback to my login controller.
Here is my login controller (Auth.php) :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('user_m');
if ($this->session->userdata('akses') == 'admin') {
redirect('dashboard');
}
elseif ($this->session->userdata('akses')=='user') {
redirect('user');
}
}
public function index() {
$this->load->view('login_v');
}
public function login() {
$nip=$this->input->post('nip');
$password=$this->input->post('password');
$query = $this->user_m->login($nip);
if ($query->num_rows()==1)
{
$row = $query->row();
if ($password == $this->bcrypt->check_password($password,$row->password)) {
$data_login= array(
'nip'=>$row->nip,
'id_pegawai'=>$row->id_pegawai,
'akses'=>$row->akses
);
echo $this->session->set_userdata($data_login);
$akses = $this->session->userdata('akses');
if ($akses=='admin') {
redirect('dashboard');
}
elseif ($akses=='user') {
redirect('user');
}
}
else {
echo "<script>alert('Gagal login: Cek nip, password!');history.go(-1);</script>";
}
}
else {
echo "<script>alert('Gagal login: Cek nip, password!');history.go(-1);</script>";
}
}
}
?>
Can anyone help me?
UPDATE
When I checked the session after redirect, it always pass a null value with new id session. Even I tried the native session class still didn't help it.

Codeigniter Session returning 310 redirect

I have a callback function that checks my login details are correct - If they are wrong it returns an error (this is working fine). If the details are correct it should set the session $this->session->set_userdata('logged_in',TRUE); and then continue with the function login and be redirected to the dashboard - This redirect works fine.
In my function index(){} on any dashboard pages have the line
if($this->session->userdata('logged_in')) redirect('dashboard/home');
The line above is the one that is causing my 310 redirect but I am unsure why?
I am wanting to check if the user is logged in redirect to dashboard/home else go back to the login page home/login
Controller:
class Home extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index()
{
//if($this->session->userdata('logged_in')) redirect('dashboard/home');
$data['contentMangement'] = $this->options_model->systemOptions();
$data['pageTitle'] = 'Login';
$data['message'] = "";
$this->load->view('_assets/header', $data);
$this->load->view('login', $data);
$this->load->view('_assets/footer');
}
public function login() {
$this->form_validation->set_rules('userEmail','Username', 'required|valid_email|trim|max_length[99]|xss_clean');
$this->form_validation->set_rules('userPassword','Password', 'required|trim|max_length[200]|xss_clean|callback__checkUsernamePassword');
if($this->form_validation->run() === FALSE) {
$data['contentMangement'] = $this->options_model->systemOptions();
$data['pageTitle'] = 'Login';
$data['message'] = validation_errors('<div class="alert alert-error">', '</div>');
$this->load->view('_assets/header', $data);
$this->load->view('login', $data);
$this->load->view('_assets/footer');
}elseif($this->form_validation->run() === TRUE){
redirect('dashboard/home');
}
}
function _checkUsernamePassword() {
$username = $this->input->post('userEmail');
$password = $this->input->post('userPassword');
$user = $this->user_model->check_login($username,$password);
if(! $user)
{
$this->form_validation->set_message('_checkUsernamePassword', 'Sorry the details you provided have not been found');
return FALSE;
}else{
$this->session->set_userdata('logged_in',TRUE);
return TRUE;
}
}
}
Here's what's happening.
Assume, I login correctly, in your login controller, you set logged_in = TRUE, and redirect me to dashboard/home. In the index() function at dashboard/home, if logged_in = TRUE (which it is) you redirect me to dashboard/home again. Once again, you check logged_in = TRUE, and redirect me again, and so on and so forth.
This is causing an infinite redirection loop which causes the 310 Error (Too many redirects).
You'll need to rework your login check. In index() in dashboard/home, do this:
if ($this->session->userdata('logged_in') === FALSE) redirect(site_url('dashboard/login'));
Now, when I visit dashboard home, you only redirect me away if I'm not logged in. This protects your dashboard home against non-authenticated users, while not throwing authenticated users into an infinite loop.
I think you first should create a MY_Controller to do that, what if one day you decide to change your session variable name from logged_in to logged? Will you open all your controllers and change its sessions?
Creating a MY_Controller you will make all other controllers, like Home_Controller extend the MY_Controller, like:
class Home extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
}
Your MY_Controller:
//under /application/core/
class MY_Controller extends Controller
{
public function __construct()
{
parent::__construct();
if(!$this->session->userdata('logged_in'))
redirect('login');
}
}
Of course that on your Login_Controller you will extend Controller and not MY_Controller or you'll be on a infinite loop.

Categories