Reputation: 3285
I am autoloading the 'session library' using autoload.php.
I am setting my user data in my controller with the following code in my Users/Login
method.
$teacher_data = [
'teacher_id' => $user_id,
'username' => $username,
'logged_in' => true
];
$this->session->set_userdata($teacher_data);
Now I simply want to check whether a user is logged in on my restricted pages using the following...
if (!$this->session->userdata('login_in')) {
redirect('home/login');
}
In my other controller, called 'Classes' I have the following code...
class Classes extends CI_Controller
{
public function create()
{
if (!$this->session->userdata('login_in')) {
echo 'not logged in';
}
}
}
The code redirects a user back to the login if they dont have permission to view the page, great... however when I add in a constructor... even an empty one like this...
class Classes extends CI_Controller
{
public function __construct()
{
}
public function create()
{
if (!$this->session->userdata('login_in')) {
echo 'not logged in';
}
}
}
I get a fatal error:
A PHP Error was encountered Severity: Notice Message: Undefined property: Classes::$session Filename: controllers/Classes.php Line Number: 12 Backtrace: File: C:\xampp\htdocs\php\toucan_app\App\controllers\Classes.php Line: 12 Function: _error_handler File: C:\xampp\htdocs\php\toucan_app\index.php Line: 315 Function: require_once Fatal error: Call to a member function userdata() on null in C:\xampp\htdocs\php\toucan_app\App\controllers\Classes.php on line 12 A PHP Error was encountered Severity: Error Message: Call to a member function userdata() on null Filename: controllers/Classes.php Line Number: 12 Backtrace:
Why is the constructor causing errors? Ultimately I want to add the 'is logged in' check to the class constructor so that I don't have to add it to each single method and thereby protect an entire class.
Upvotes: 0
Views: 1537
Reputation: 1658
You can change your code in set data in session variable :
$teacher_data = array(
'teacher_id' => $user_id,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($teacher_data);
after you can check login login variable:
class Classes extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function create()
{
if (!$this->session->userdata('logged_in')) {
echo 'not logged in';
}
}
}
Upvotes: 1
Reputation: 3588
Parent __constructs
are not implicitly called when a child class has a __construct
method of it's own.
You need to call parent::__construct()
in the child class's construct in order for it to work properly.
See here for the code related to the CodeIgniter's Controller construct.
Upvotes: 1