-2

i have a problem in a controller file called "pages.php". After login via login page with correct credentials pages.php does not open dashboard. I doubt that probably the source of this problem may be found in this pages.php

<?php 
class Pages extends MY_Controller
{
public function view($page = 'login')
{
    if (!file_exists(APPPATH.'views/'.$page.'.php'))
    {
        // Whoops, we don't have a page for that!
        show_404();
    }

    $data['title'] = ucfirst($page); // Capitalize the first letter

    if($page == 'section' || $page == 'subject' || $page == 'student' || $page == 'marksheet' || $page == 'accounting') {
        $this->load->model('model_classes');
        $data['classData'] = $this->model_classes->fetchClassData();

        $this->load->model('model_teacher');
        $data['teacherData'] = $this->model_teacher->fetchTeacherData();


        $this->load->model('model_accounting');
        $data['totalIncome'] = $this->model_accounting->totalIncome();
        $data['totalExpenses'] = $this->model_accounting->totalExpenses();
        $data['totalBudget'] = $this->model_accounting->totalBudget();
    }

    if($page == 'setting') {
        $this->load->model('model_users');
        $this->load->library('session');
        $userId = $this->session->userdata('id');
        $data['userData'] = $this->model_users->fetchUserData($userId);
    }

    if($page == 'dashboard') {
        $this->load->model('model_student');
        $this->load->model('model_teacher');
        $this->load->model('model_classes');
        $this->load->model('model_marksheet');
        $this->load->model('model_accounting');

        $data['countTotalStudent'] = $this->model_student->countTotalStudent();
        $data['countTotalTeacher'] = $this->model_teacher->countTotalTeacher();
        $data['countTotalClasses'] = $this->model_classes->countTotalClass();
        $data['countTotalMarksheet'] = $this->model_marksheet->countTotalMarksheet();

        $data['totalIncome'] = $this->model_accounting->totalIncome();
        $data['totalExpenses'] = $this->model_accounting->totalExpenses();
        $data['totalBudget'] = $this->model_accounting->totalBudget();
    }

    if($page == 'login') {
        $this->isLoggedIn();
        $this->load->view($page, $data);
    } 
    else{
        $this->isNotLoggedIn();

        $this->load->view('templates/header', $data);
        $this->load->view($page, $data);    
        $this->load->view('templates/footer', $data);    
    }
}

}

Please anyone who can edit this code just help. Or if you think the problem is not in pages.php (above page) please advice me how the problem can be solved. I have mentioned more pages:-

This is rootes.php.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';


$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

This is MY_Controller.php in core folder

<?php 
class MY_Controller extends CI_Controller 
{
public function __construct()
{
    parent::__construct();
}

public function isLoggedIn()
{

    $this->load->library('session');

    if($this->session->userdata('logged_in') === true) {
        redirect('../dashboard');
    }
}   

public function isNotLoggedIn()
{

    $this->load->library('session');

    if($this->session->userdata('logged_in') != true) {
        redirect('../../');
    }
}

}

This is Users.php in controllers folder

<?php 
class Users extends MY_Controller
{
public function __construct()
{
    parent::__construct();

    // loading the users model
    $this->load->model('model_users');

    // loading the form validation library
    $this->load->library('form_validation');        

}

public function login()
{

    $validator = array('success' => false, 'messages' => array());

    $validate_data = array(
        array(
            'field' => 'username',
            'label' => 'Username',
            'rules' => 'required|callback_validate_username'
        ),
        array(
            'field' => 'password',
            'label' => 'Password',
            'rules' => 'required'
        )
    );

    $this->form_validation->set_rules($validate_data);
    $this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');

    if($this->form_validation->run() === true) {            
        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));

        $login = $this->model_users->login($username, $password);

        if($login) {
            $this->load->library('session');

            $user_data = array(
                'id' => $login,
                'logged_in' => true
            );

            $this->session->set_userdata($user_data);

            $validator['success'] = true;
            $validator['messages'] = "index.php/dashboard";             
        }   
        else {
            $validator['success'] = false;
            $validator['messages'] = "Incorrect username/password combination";
        } // /else

    }   
    else {
        $validator['success'] = false;
        foreach ($_POST as $key => $value) {
            $validator['messages'][$key] = form_error($key);
        }           
    } // /else

    echo json_encode($validator);
} // /lgoin function

public function validate_username()
{
    $validate = $this->model_users->validate_username($this->input->post('username'));

    if($validate === true) {
        return true;
    } 
    else {
        $this->form_validation->set_message('validate_username', 'The {field} does not exists');
        return false;           
    } // /else
} // /validate username function

public function logout()
{
    $this->load->library('session');
    $this->session->sess_destroy();
    redirect('../../');
}


public function updateProfile()
{
    $this->load->library('session');
    $userId = $this->session->userdata('id');

    $validator = array('success' => false, 'messages' => array());

    $validate_data = array(
        array(
            'field' => 'username',
            'label' => 'Username',
            'rules' => 'required'
        ),
        array(
            'field' => 'fname',
            'label' => 'First Name',
            'rules' => 'required'
        )
    );

    $this->form_validation->set_rules($validate_data);
    $this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');

    if($this->form_validation->run() === true) {    
        $update = $this->model_users->updateProfile($userId);                   
        if($update === true) {
            $validator['success'] = true;
            $validator['messages'] = "Successfully Update";
        }
        else {
            $validator['success'] = false;
            $validator['messages'] = "Error while inserting the information into the database";
        }           
    }   
    else {
        $validator['success'] = false;
        foreach ($_POST as $key => $value) {
            $validator['messages'][$key] = form_error($key);
        }           
    } // /else

    echo json_encode($validator);
}

public function changePassword()
{
    $this->load->library('session');
    $userId = $this->session->userdata('id');

    $validator = array('success' => false, 'messages' => array());

    $validate_data = array(
        array(
            'field' => 'currentPassword',
            'label' => 'Current Password',
            'rules' => 'required|callback_validate_current_password'
        ),
        array(
            'field' => 'newPassword',
            'label' => 'Password',
            'rules' => 'required|matches[confirmPassword]'
        ),
        array(
            'field' => 'confirmPassword',
            'label' => 'Confirm Password',
            'rules' => 'required'
        )
    );

    $this->form_validation->set_rules($validate_data);
    $this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');     

    if($this->form_validation->run() === true) {    
        $update = $this->model_users->changePassword($userId);                  
        if($update === true) {
            $validator['success'] = true;
            $validator['messages'] = "Successfully Update";
        }
        else {
            $validator['success'] = false;
            $validator['messages'] = "Error while inserting the information into the database";
        }           
    }   
    else {
        $validator['success'] = false;
        foreach ($_POST as $key => $value) {
            $validator['messages'][$key] = form_error($key);
        }           
    } // /else

    echo json_encode($validator);
}

public function validate_current_password()
{
    $this->load->library('session');
    $userId = $this->session->userdata('id');
    $validate = $this->model_users->validate_current_password($this->input->post('currentPassword'), $userId);

    if($validate === true) {
        return true;
    } 
    else {
        $this->form_validation->set_message('validate_current_password', 'The {field} is incorrect');
        return false;           
    } // /else  
}

}

This is login.php in views folder

<!DOCTYPE html>
<html>
<head>
<title><?php echo $title; ?></title>

<!-- bootstrap css -->
<link rel="stylesheet" type="text/css" 
href="assets/bootstrap/css/bootstrap.min.css">
<!-- boostrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">

<!-- custom css -->
<link rel="stylesheet" type="text/css" href="custom/css/custom.css">    

<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- boostrap js -->
<script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js">
</script>

</head>
<body>


<div class="col-md-6 col-md-offset-3 vertical-off-4">
<div class="panel panel-default login-form">
    <div class="panel-body">
        <form method="post" action="index.php/users/login" id="loginForm">
            <fieldset>
                <legend>
                    Login
                </legend>

                <div id="message"></div>

                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" class="form-control" id="username" name="username" placeholder="Username" autofocus>
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                </div>                                           

                <button type="submit" class="col-md-12 btn btn-primary login-button">Submit</button>                    
            </fieldset>
        </form>
    </div>
</div>
</div>

<script type="text/javascript" src="custom/js/login.js"></script>
</body>
</html>

login.js

$(document).ready(function(){
$("#loginForm").unbind('submit').bind('submit', function() {

    var form = $(this);
    var url = form.attr('action');
    var type = form.attr('method');

    $.ajax({
        url  : url,
        type : type,
        data : form.serialize(),
        dataType: 'json',
        success:function(response) {
            if(response.success === true) {
                window.location = response.messages;
            }
            else {
                if(response.messages instanceof Object) {
                    $("#message").html('');     

                    $.each(response.messages, function(index, value) {
                        var key = $("#" + index);

                        key.closest('.form-group')
                        .removeClass('has-error')
                        .removeClass('has-success')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger').remove();                         

                        key.after(value);

                    });
                } 
                else {                      
                    $(".text-danger").remove();
                    $(".form-group").removeClass('has-error').removeClass('has-success');

                    $("#message").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                      '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                      response.messages + 
                    '</div>');
                } // /else
            } // /else
        } // /if
    });

    return false;
});
});
  • Can u please show how u are defining `$page` and where the values of `$this->isLoggedIn() and $this->isNotLoggedIn()` – Francisco Hahn Feb 07 '18 at 20:41
  • @Francisco Hahn, I have edited the question, pse I need help – AbuuJurayj Swabur Buruhan Feb 07 '18 at 21:11
  • 1
    @AbuuJurayj try not to post a lot of code in your comment re edit your question instead. –  Feb 07 '18 at 23:59
  • This is way too much code. I shouldn't have to work to find relevant info. – Alex Feb 10 '18 at 01:04
  • @alex, I suggested to mention all related pages to this problem because I have failed to detect where the source of problem is. – AbuuJurayj Swabur Buruhan Feb 11 '18 at 12:10
  • Well the problem is not going to be in your view. It's not going to be in your validate password methods. What is actually happening when you login with correct credentials? What is the output of Json encode for the login function. Do you get redirected at all? I'd be more interested in seeing your js function that handles this login.js – Alex Feb 11 '18 at 19:53
  • @alex I have edited the question, login.js is also there. The problem is that the **login page** does not redirect me to **dashboard** after login with correct credentials and also no any error appearing at all. – AbuuJurayj Swabur Buruhan Feb 12 '18 at 04:19
  • What happens after you login? Does it redirect at all, give you a blank screen, show you the meaning of life? – Alex Feb 12 '18 at 04:28
  • These questions will help us narrow it down so we can find a solution. The last option was a joke btw haha – Alex Feb 12 '18 at 08:17
  • so sorry @Alex I was offline for 2 days ago, After login with correct credentials the login page **only refresh and return itself** without displaying any error or blank page. (It does not redirect at all but refreshing only) – AbuuJurayj Swabur Buruhan Feb 15 '18 at 05:46
  • We need to figure out a couple things: (1) is the login js function actually getting hit. Try a this https://pastebin.com/XMMYSheq (just a bunch of console logs). (2) if that is ok, and we are getting a response with a redirect url, then try in `public function view()` add a `print_r($_SESSION); exit;` at the top (above everything in the func) to see if we are getting the session vars. The page just refreshing really sounds to me like (1) might be the issue, for some reason the submit isn't doing the ajax process. – Alex Feb 16 '18 at 08:05
  • 1
    @alex thanks for your support – AbuuJurayj Swabur Buruhan Feb 19 '18 at 06:22

3 Answers3

0

Thanks to all, finally I have got a correct answer, the problem was due to the older version of codeignitor in php 7 server, for more info click

Codeigniter session data lost after redirect

0

Hi I was facing same issue. logs was showing nothing and my apache server got hanged. but in my case issue was with my controller. i did one mistake. i was printing array object in logs. instead of doing array to string conversion. i solved this and redirect function started working.

0

Just use refresh method, it works for me

$this->load->helper('url);
redirect('foo', 'refresh');