Reputation: 21749
When user logins or when he registers, his $_SESSION['username']
gets the value of his username. I want to allow them access certain controllers only if they registered. But I don't like the idea of writing this:
function __construct()
{
session_start();
if(empty($_SESSION['username']))
die();
parent::__construct();
}
in every controller I don't want unloggined people to see. Is there any better way to do it? Thanks.
Upvotes: 0
Views: 4041
Reputation: 16510
You might consider extending your base controller class (see the Codeigniter Wiki Article on extending the class) to provide a require_login
function:
class MY_Controller extends CI_Controller {
protected function require_login() {
if(empty($_SESSION['username']))
die();
}
}
Once you have this, you can call require_login()
in the constructor of each controller you want to protect:
function __construct() {
$this->require_login();
}
Finally, instead of using PHP's $_SESSION
superglobal for session storage, you might consider taking advantage of the Codeigniter session
library or an equivalent.
Upvotes: 4
Reputation: 683
function __construct() {
parent::Controller();
$this->authenticate();
}
function authenticate()
{
if (!$this->session->userdata('admin_loggedIn'))
{
redirect('login');
}
}
Upvotes: 1
Reputation: 197775
Codeigniter has it's own session, not $_SESSION
.
Apart from that, if you have controller that are of the same type, you can write a base controller and extend from it. The base controller than could contain the code to validate if the controller is accessible and you don't need to write that in each controller class you create. See How do I extend the code igniter controller class?.
Upvotes: 1