To restrict access to pages one can check like below,
//This code is written on every page accessed by admin. Like, products.php, categories.php
if( !isset($_SESSION['admin_id'])) {
header('Location: admin/login.php');
exit();
}
What is the equivalent of the above code in Codeigniter, if i want to restrict access to every methods of the controller?
can i check for session in constructor like below?
//products.php
class Products extends CI_Controller {
public function __construct();
if( !isset($_SESSION['admin_id'])) {
redirect('admin/login.php');
}
}
//categories.php
class Categories extends CI_Controller {
public function __construct();
if( !isset($_SESSION['admin_id'])) {
redirect('admin/login.php');
}
}
a Simple way I usually use.
Create a controller in
application/core
asAdmin_Controller.php
and Extend it from the base controller,CI_Controller
as,Then, Extend your other admin related controllers from
Admin_Controller.php
as,Now, you don't need to check in every
__contructor()
method whether admin or not. Also some methods such as login, logout which don't need auth check will be skipped.Hope this helps :)