简体   繁体   中英

The page isn’t redirecting properly

I get this kind of error when I create a redirect library I named it redirector.php also I already run it in autoload.php

this is my redirector.php

class Redirector{
    protected $CI;

    public function __construct(){
        //needed for every libraries
        $this->CI =& get_instance();

        $userid = $this->CI->session->userdata('userid');

        if(isset($userid)){
            redirect('/rey');
        }else{
            redirect('/log_in');
        }
    }
}

this is my log_in controller

if($check){
    $arr = array(
        'userid' => $check->id,
        'username' => $username,
        'password' => $password
    );

    $this->session->set_userdata($arr);
    //redirect('/rey','refresh');
}else{
    echo "<p>User does not exist</p>";
}

PS I just get this kind of error when I make it in library but if I put this code in every constructor every file except log_in.php I didnt get an error

$userid = $this->session->userdata('username');
        if(empty($userid)){
            redirect('/log_in','refresh');
        }

edited

I got no error in redirect in my index which is log_in but if I set the session it didnt redirect to rey.php this is what i have done.

if(empty($userid) && $this->CI->uri->segment(1) != 'log_in'){
            redirect('/log_in');
        }else{
            if(isset($userid) && $this->CI->uri->segment(1) === 'log_in'){
                redirect('/rey');
            }
        }

Your redirector.php will run before all controllers.. So the code redirect will work before your login controller.. So it will redirected too many times.. Checking login on every controller is better.

If you still want use this library change your code to this..

class Redirector{
    protected $CI;

    public function __construct(){
        //needed for every libraries
        $this->CI =& get_instance();

        $userid = $this->CI->session->userdata('userid');

        if(empty($userid) && $this->CI->uri->segment(1) != 'log_in'){
            redirect('/log_in');
        }

        if(!empty($userid) && $this->CI->uri->segment(1) == 'log_in'){
            redirect('/rey');
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM