I am writing a web application using codeigniter.
I want to authenticate the privilege of our users before they access the page.
Actually nearly all controller action except the log in page need to call the model and use
$this->Users->validate($username, $password)
I want to make it general for every controller. Do I need to inherit the controller class? How could i do that?
We have a project using Codeigniter and the way we are doing it :
When you have a new controller :
class xxxx extends MY_Controller { }
And Inside the MY_Controller class
function __construct() {
// do your validations
}
The best way is that you should make a helper file in your application/helper folder with this name or any of you want but don't remove _helper , you should use this name authentication_helper , and put the following code as yours
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function varify_session(){
$CI = &get_instance();
$user_session_id = $CI->session->userdata('logged_in');
if($user_session_id == '') {
redirect('login');
}
}
?>
chage code with yours code. then in your autoload file and in put this into helper
$autoload['helper'] = array('authentication');
then you just need to put this line into your every controller constructor like this
function __construct()
{
parent::__construct();
varify_session();
}
hope it will help.
please write below code in constructor of each controller
$this->load->library(‘session’);
$this->load->model(‘login_model’,'login’,TRUE);
/* check whether login or not */
if(!$this->login->check_session()){
redirect(‘/login’);
}
Correct before filter usage:
class Test extends Controller {
var $before_filter = array();
var $after_filter = array();
function __construct() {
parent::Controller();
$this->before_filter[] = array(
'action' => 'before_filter_run',
);
}
function before_filter_run() {
// Auth here
}
}
For details read here
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.