skip to Main Content

When I click on Login button, 1) then login successfully message appears. 2) I also checked session is created successfully as I put response line $resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url); inside condition if ($this->session->has_userdata('email')), it shows session is also created. 3) I also checked overall code and debug the code in browser also. I cannot find out any reason why it comes back to the login page. That’s why I am here for your assistance. I attached relevent View file code, Controller code as well as js file code so that anyone can test it. Looking forward to your guideance

Issue that I traced till now is related to session:
at location.href = resp.url; when I provided the url that is not linked to the session, it goes to that url immediately. When I put this admin/bashboard with base url. Then it comes back. Why session is destorying, I cannot find the reason till now.

Session Settings in Config.php file

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session_alhuda';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = BASEPATH . '/cache/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

In view Login.php

<form class="form" method="post" action="<?php echo base_url().'front_ajax/login'; ?>" data-redirect="yes">
    <div class="edu_field_holder">
        <input type="text" class="edu_form_field require" name="email" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_p_email'));?>" autocomplete="off" value="<?php echo(isset($_COOKIE['UML'])) ? base64_decode(urldecode(base64_decode($_COOKIE['UML']))) : ''; ?>">
    </div>
    <div class="edu_field_holder">
        <input type="password" name="password" class="require edu_form_field" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_password'));?>" value="<?php echo(isset($_COOKIE['SSD'])) ? base64_decode(urldecode(base64_decode($_COOKIE['SSD']))) : ''; ?>">
    </div>
    
    <div class="col-lg-6 col-md-6 col-sm-12 col-12 text-md-right">
        <button class="edu_btn edu_btn_black" id="auth_login" type="button" data-action="submitThisForm"><?php echo html_escape($this->common->languageTranslator('ltr_login'));?></button>
    </div>      
</form>

In Controller Front_ajax.php

function login(){
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')){
        if(!empty($this->input->post('email',false)) && !empty($this->input->post('password',false))){          
            $email = trim($this->input->post('email',TRUE));
            $pass = md5(trim($this->input->post('password',TRUE)));     
            if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
                $stud_cond = array('enrollment_id'=>$email,'password'=>$pass);
            }else{
                $stud_cond = array('email'=>$email,'password'=>$pass);
            }
            $userDetails = $this->db_model->select_data('id,name,role,status,parent_id,teach_image,email,teach_batch,teach_subject,super_admin','users use index (id)',array('email'=>$email,'password'=>$pass),1);
            $studentDetails = $this->db_model->select_data('id,name,contact_no,batch_id,admin_id,enrollment_id,image,email,status,login_status','students use index (id)',$stud_cond,1);          
            $this->session->sess_destroy();
            if(!empty($userDetails)){
                  if($userDetails[0]['status']=='1'){
                    $brewers_strings = $this->random_strings(10);
                    $sess_arr = array(
                                'uid'=> $userDetails[0]['id'],
                                'name'=> $userDetails[0]['name'],
                                'role'=> $userDetails[0]['role'],
                                'status'=> $userDetails[0]['status'],
                                'admin_id' => $userDetails[0]['parent_id'],
                                'profile_img' => $userDetails[0]['teach_image'],
                                'email' => $userDetails[0]['email'],
                                'mobile' => $userDetails[0]['contact_no'],
                                'brewers_check' => $brewers_strings,
                                'super_admin' => $userDetails[0]['super_admin'],
                               
                            );
                        
                    $url = '';
                        $url = base_url().'admin/dashboard';
                                            
                    $this->session->set_userdata($sess_arr);
                        
                    $resp = array('status'=>'1','msg'=>$this->lang->line('ltr_logged_msg'),'url'=>$url);//
                    
                    $this->db_model->update_data_limit('users use index (id)',$this->security->xss_clean(array('token'=>1,'brewers_check'=>$brewers_strings)),array('id'=>$userDetails[0]['id']),1);
                  }else{
                    $resp = array('status' => '0','msg' =>$this->lang->line('ltr_contact_to_admin_msg'));//
                }
            }
            else{
                $resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
            }
        }
        else{
            $resp = array('status' => '0','msg' =>$this->lang->line('ltr_wrong_credentials_msg'));
        }
        echo json_encode($resp,JSON_UNESCAPED_SLASHES);
    }
    else{
        echo $this->lang->line('ltr_not_allowed_msg');
    } 
}

In login.js

$(document).ready(function(){
$('[data-action="submitThisForm"]').on('click' , function(){
    var targetForm = $(this).closest('form');
    if(!myCustom.checkFormFields(targetForm)){
        myCustom.callFormAjax(targetForm).done(function(res){
            var resp = $.parseJSON(res);
            if(resp.status == 1){
                if(typeof targetForm.attr('data-reset') != 'undefined' && targetForm.attr('data-reset') == 1){ //check reset form data
                    targetForm[0].reset();
                }
                if(typeof targetForm.attr('data-redirect') != 'undefined'){ //check reset form data
                    if(resp.msg != '')
                        toastr.success(resp.msg)
                    setTimeout(function(){
                        location.href = resp.url;   
                    },1500)
                }else if(resp.msg){
                    toastr.success(resp.msg);
                }
            }else if(resp.status == 2){
                $.magnificPopup.open({
                    items: {
                        src: '#studentLogin',
                    },
                    type: 'inline'
                });
                $('#studentLogin .changeStudentLogin').attr('data-id',resp.student_id);
            }
            else if(resp.status == 0){
                toastr.error((resp.msg)?resp.msg:resp.error);
            }
        });
    }
});

2

Answers


  1. login.php

           <form class="form" method="post" action="<?php echo base_url('front_ajax/login'); ?>" data-redirect="yes">
            <div class="edu_field_holder">
                <input type="text" class="edu_form_field require" name="email" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_p_email'));?>" autocomplete="off" value="<?php echo (isset($_COOKIE['UML'])) ? base64_decode(urldecode(base64_decode($_COOKIE['UML']))) : ''; ?>">
            </div>
            <div class="edu_field_holder">
                <input type="password" name="password" class="require edu_form_field" placeholder="<?php echo html_escape($this->common->languageTranslator('ltr_password'));?>" value="<?php echo (isset($_COOKIE['SSD'])) ? base64_decode(urldecode(base64_decode($_COOKIE['SSD']))) : ''; ?>">
            </div>
            
            <div class="col-lg-6 col-md-6 col-sm-12 col-12 text-md-right">
                <button class="edu_btn edu_btn_black" id="auth_login" type="button" data-action="submitThisForm"><?php echo html_escape($this->common->languageTranslator('ltr_login'));?></button>
            </div>      
        </form>
        
        Controller Method:
        
        public function login(){
            if($this->input->is_ajax_request()){
                $email = trim($this->input->post('email', TRUE));
                $password = trim($this->input->post('password', TRUE));
        
                if(!empty($email) && !empty($password)){
                    // Use password_hash in the registration process and password_verify here
                    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
                        $user = $this->db_model->select_data('id, name, role, status, parent_id, teach_image, email, password, contact_no, super_admin', 'users', array('email' => $email), 1);
                    } else {
                        $user = $this->db_model->select_data('id, name, contact_no, batch_id, admin_id, enrollment_id, image, email, password, status, login_status', 'students', array('enrollment_id' => $email), 1);
                    }
        
                    if(!empty($user) && password_verify($password, $user[0]['password'])){
                        if($user[0]['status'] == '1'){
                            $session_data = array(
                                'uid' => $user[0]['id'],
                                'name' => $user[0]['name'],
                                'role' => $user[0]['role'],
                                'status' => $user[0]['status'],
                                'admin_id' => isset($user[0]['parent_id']) ? $user[0]['parent_id'] : $user[0]['admin_id'],
                                'profile_img' => isset($user[0]['teach_image']) ? $user[0]['teach_image'] : $user[0]['image'],
                                'email' => $user[0]['email'],
                                'mobile' => $user[0]['contact_no'],
                                'brewers_check' => $this->random_strings(10),
                                'super_admin' => isset($user[0]['super_admin']) ? $user[0]['super_admin'] : null
                            );
        
                            $this->session->set_userdata($session_data);
        
                            // Update user session token
                            $this->db_model->update_data('users', array('token' => 1, 'brewers_check' => $session_data['brewers_check']), array('id' => $user[0]['id']));
        
                            $resp = array('status' => '1', 'msg' => $this->lang->line('ltr_logged_msg'), 'url' => base_url('admin/dashboard'));
                        } else {
                            $resp = array('status' => '0', 'msg' => $this->lang->line('ltr_contact_to_admin_msg'));
                        }
                    } else {
                        $resp = array('status' => '0', 'msg' => $this->lang->line('ltr_wrong_credentials_msg'));
                    }
                } else {
                    $resp = array('status' => '0', 'msg' => $this->lang->line('ltr_wrong_credentials_msg'));
                }
        
                echo json_encode($resp, JSON_UNESCAPED_SLASHES);
            } else {
                echo $this->lang->line('ltr_not_allowed_msg');
            }
        }
    
    Updated JavaScript (login.js):
    
    $(document).ready(function(){
        $('[data-action="submitThisForm"]').on('click', function(){
            var targetForm = $(this).closest('form');
            if(!myCustom.checkFormFields(targetForm)){
                myCustom.callFormAjax(targetForm).done(function(res){
                    var resp = $.parseJSON(res);
                    if(resp.status == 1){
                        if(targetForm.attr('data-reset') == '1'){ // Reset form if required
                            targetForm[0].reset();
                        }
                        if(targetForm.attr('data-redirect') !== undefined){ // Redirect if required
                            if(resp.msg != '')
                                toastr.success(resp.msg);
                            setTimeout(function(){
                                location.href = resp.url;   
                            }, 1500);
                        } else if(resp.msg){
                            toastr.success(resp.msg);
                        }
                    } else if(resp.status == 2){
                        $.magnificPopup.open({
                            items: {
                                src: '#studentLogin',
                            },
                            type: 'inline'
                        });
                        $('#studentLogin .changeStudentLogin').attr('data-id', resp.student_id);
                    } else if(resp.status == 0){
                        toastr.error(resp.msg ? resp.msg : resp.error);
                    }
                });
            }
        });
    });
    
    Login or Signup to reply.
  2. I faced same issue earlier due to session handling.

    In your provided code it seems either the session handling or the redirection logic that you implement.

    First of all please check the session setting is properly configured in config.php file

    • 'sess_driver' should be set to 'files'
    • 'sess_save_path' must be a valid directory if using the file driver
    • 'base_url' should be correctly set in 'config.php'
    • 'sess_expiration' should not be too short at least 7200 // for 2 hours

    Next, If your application is redirecting between HTTP and HTTPS, or between different domains or subdomains, it could cause issues with session persistence. Make sure that the session cookie is being properly shared across requests

    Also, in your JS code location.href = resp.url; try to add a below debug statement which define the correct URL is processed

        setTimeout(function(){
        console.log('Redirecting to: ' + resp.url);
        location.href = resp.url;
    }, 1500);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search