1

I am working with Codeigniter PHP.

I want if admin not login then he can't see admin panel pages. For this i created helper.

The Code is working if I put condition is every function but if I use this code in "constructor" then redirect to home page but also showing "login" page after home page.

Where I am wrong ?

Here is my code (using in one of my function which is working )

public function admin_offers(){
        if (!is_logged_in()) {
            $this->index();
            //die();
        }
        else {
            $data['offers']=$this->db->get('offers')->result();
            $this->load->view('admin/special-offers',$data);
        }
    }

And here is my code in constructor, which is not working for me.

public function __construct() {
    

    parent::__construct();
        $this->load->model("stores_model");
            $this->load->library("pagination");
            $this->load->library('encryption');
            is_logged_in(); 
            if (!is_logged_in()) {
                $this->index();
            }
}

1 Answer 1

1

First, from your code, you are calling the function twice which is unnecessary.

is_logged_in(); //this calls the function
if (!is_logged_in() /* this too */) {
    $this->index();
}

For your case, try this:

function __construct(){
  parent::__construct();
    $this->load->model("stores_model");
    $this->load->library("pagination");
    $this->load->library('encryption');
     
    if (!$this->session->user_data('session_name')) {
        redirect('controller_name/function'); // the public page
     }
}

Basically, what the code does, it checks if the session data(set during login) exists, if it does not exist, the user is redirected to the public page(possibly the login page).

If you place the code under the __construct function, no need to include it in individual functions as this code is executed when the class is instantiated, hence executed before the functions are loaded.

NB: Make sure you have already loaded session library in autoload

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.