Codeigniter constructor - check if user is logged in - php

I am attempting to create a constructor for my controller that references a function that I have contained in a helper which is autoloaded.
The function checks whether or not the user is logged in, if so it redirects them to the login page.
It appears that I have not setup the construct correctly as I am receiving the following error:
Fatal error: Call to undefined method Profile::is_logged_in()
This is the controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
//function inside autoloaded helper, check if user is logged in, if not redirects to login page
$this->is_logged_in();
}
public function index() {
echo 'hello';
}
}
I only want to make function within the controller accessible if the user is logged in.
This is the helper which is autoloaded
$autoload['helper'] = array('url','array','html','breadcrumb','form','function','accesscontrol');
(accesscontrol_helper.php):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. Login';
die();
//$this->load->view('login_form');
}
}
Why would I not be able to run the function? Is containing the code in the helper the best method?

As other already mentioned, helpers are simply a collection of functions. Expanding on them:
since they're loaded more than once sometimes, you need to specify not to declare a function if already present, all you'll raise an error.
You cannot, moreover, call a CI's class inside them without first instantiating the main CI object. This is a more proper way to use your helper function:
if(!function_exists('is_logged_in'))
{
function is_logged_in()
{
$CI =& get_instance();
$is_logged_in = $CI->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. Login';
die();
}
}
}
I would also have it return instead of echo, and move the die() to the controller, but this is another story.

Helpers are just included functions, so you don't need to access it with $this. Just call it as a normal function:
is_logged_in();

You don't call a helper function using $this. Just do is_logged_in();
public function __construct()
{
parent::__construct();
//function inside autoloaded helper, check if user is logged in, if not redirects to login page
is_logged_in();
}

accesscontrol_helper.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Accesscontrol_helper{
function is_logged_in()
{
//code
}
}
in Profile controller:
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
Accesscontrol_helper::is_logged_in();
}
}

Related

Codeigniter 3 MY_Controller

I have this on my MY_Controller that was located on my core folder.
<?php
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function is_logged_in($data){
$session = $this->session->userdata();
if($session['isloggedin']['username'] == ''){
return isset($session);
}else{
return FALSE;}
}
}
?>
I'm pretty sure i copy pasted the above code from some tutorial and i haven't gotten to editing it based on my needs.
Any case i have questions.
So i have a pages controller that will be responsible for giving access to some views depending on the account_type of the logged in user.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class pages extends MY_Controller {
}?>
this is my session whenever a user logs in.
$new_session = array( 'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'type' => $this->input->post('type'),
'logged_in' => TRUE);
$this->session->set_userdata($new_session);
How do i call the MY_controller function is_logged_in() from the pages controller or is the 'extends MY_Controller' automatically also calls the function is_logged_in() or do i have to basically just put it in a __construct so it automatically calls the function?
Also, how do i go about checking if a user is logged in and seeing their details?
Do i pass session_data from my controller to MY_Controller? if so, how?
Or should i just put a $this->session->userdata(); line inside the is_logged_in() function?
P.S. i have tried using Authentication Libraries but they include far too much to what i need, i just need a basic authentication. Any suggestions? that is still maintained right now.
you can directly call is_logged_in() function from your pages controller. just like this:
Pages.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pages extends MY_Controller {
function __construct() {
parent::__construct(); // this will trigger the __construct() of MY_Controller
}
}
MY_Controller.php
<?php
class MY_Controller extends CI_Controller{
public function __construct() {
parent::__construct();
if( $this->is_logged_in() ) {
// do something if user is allowed to access.
}
else {
// do something if user is not allowed to access
}
}
}

Multiple View is getting loaded in verification of session variable in codeigniter

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller{
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->is_logged_in();
}
function is_logged_in()
{
$is_logged_in=$this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true){
//$this->load->view('notlogin');
$this->load->view('admin_login');
//echo "you dont have permission to access this area";
}
}
function index()
{
$this->load->view('admin_login');
//die();
}
function adminlogin()
{
$this->load->model('loginmodel');
$query=$this->loginmodel->verify();
if($query==true){
$data=array(
'username'=>$this->input->post('username'),
'is_logged_in'=>true
);
$this->session->set_userdata($data);
redirect('Login/loginarea');
}
else
{
//$this->is_logged_in();
$this->index();
}
}
public function loginarea()
{
$this->load->view('mainadmin');
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
Here two function __construct and index is loading the same view twice. I don't how to logically correct this. I am checking is_logged_in variable is true or not: if true then load admin area or else admin login page. But index function is also getting executed along with it.
When you call your controller, it will always execute the constructor and the function you have specified in the second segment or by default, index().
In your case, if we assume your URL is http://example.com/index.php/Login
The first thing to be executed is the constructor which calls $this->is_logged_in();
If we assume that the login failed, you load the view with this call $this->load->view('admin_login');
That's it for the constructor.
Then codeigniter call the default function index() which also loads a view $this->load->view('admin_login');
So, that's why your view appears two times.
Imo, the easiest way to fix this is by removing the code in index(). You are not doing anything special in that function and the view is loaded inside is_logged_in() when the constructor is executed.
However, I don't understand why do you check the user status in the controller supposed to authenticate people.
It shouldn't be done that way imho :
Actually, you check if the user is not logged. Instead, I would have have check if the user is logged then I redirect to the admin area or whatever it is.
This way, index() will be the function that displays admin_login and the constructor via is_logged_in() displays the other view.

Codeigniter: proper way to access function on custom library

I create simple library called Xauth.php to check if user already login or not:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Xauth
{
protected $ci;
public function __construct()
{
$this->ci =& get_instance();
}
public function is_logged_in()
{
if ($this->ci->session->userdata('is_logged_in'))
{
return true;
}
return false;
}
}
I put that library in my Admin_Controller, so whatever controller extended with Admin_Controller will be checked first, if the session data is empty they will be redirect to login page. And this is my Admin_Controller.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin_Controller extends MY_Controller {
public function __construct()
{
$this->load->library('Xauth');
if ($this->Xauth->is_logged_in() == false) {
redirect('auth');
}
}
}
But I got an errors, it says:
Message: Undefined property: Dashboard::$Xauth
Where is my fault?
You must use your class with lowercase letters :
$this->xauth->is_logged_in()

Forcing CodeIgniter to send view and stop working

Hello I'm using inherited controllers. These are my controllers:
-baseAdminController:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class _BaseAdminController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('session');
$calledFunction= $this->router->fetch_method();
if ($calledFunction!= 'loginView' && $calledFunction!= 'doLogin') {
$this->checkSession();
}
}
public function checkSession() {
if ($this->session->userdata('loggedIn') == false) {
$this->load->view('admin/loginView');
}
}
}
And my derived Admin Controllers:
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class AdminController extends _BaseAdminController {
public function indexView() {
$this->load->view('admin/indexView');
}
}
When i'm tring to login, CodeIgniter shows me both admin/loginView and admin/indexView. Because i'm checking session status at constructing my derived controller. How can i prevent to loading second view?
Thank in advance..
To answer your question, you could have done the following into your checkSession method:
public function checkSession() {
if ($this->session->userdata('loggedIn') == false) {
echo $this->load->view('admin/loginView', array(), TRUE);
exit;
}
}
Explanation: If you pass the third argument as TRUE, it will return the content of that file. Read ellislab.com for more info.
I hope this is related to your question:
I recently wanted to have a bunch of controllers extend a parent controller class (MY_Acl_Controller) that checked that the current logged-in user deserved access to each method (using a homegrown ACL library). The check was to be initiated in MY_Acl_Controller's constructor, so it would run on every request.
I wanted to set the Output class's output to the result of loading a view, then display the view and exit, but because this process was NOT executed in a routed controller method, I couldn't just call $this->load->view('errors/access_denied') and then return from the constructor function... CI would then carry on executing controller code.
So I created a MY_Output class, extending CI_Output, and added to it a public function display_with_exit():
public function display_with_exit()
{
$this->_display($this->final_output);
exit;
}
Then, in MY_Acl_Controller's constructor:
...
if(!$user_deserves_access)
{
$this->load->view('errors/access_denied');
$this->output->display_with_exit();
}
Maybe that might be useful to someone?
The advantage of this approach is that the Output class's _display() function sends all HTTP headers you'd like it to, as per any normal response.
Avoid exit; / function exit; or die; will terminate execution, its better practice in only debugging your code.
Try like below.
public function index(){
if($xx) return TRUE;
}

CodeIgniter 'MY_' can not be found in ... error

I have been working on a session validation for my login to make sure that a user is logged in to view pages. I keep getting this error:
Fatal error: Class 'MY_Staffcontroller' not found in /usr/local/var/www/CodeTest
/ci/application/controllers/staff_c.php on line 3
My staff_c page looks like so :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Staff_c extends MY_Staffcontroller {
function homepage()
{
$data['main_content'] = 'homepage_view';
$this->load->view('includes/template', $data);
}
}
I have been reading same questions all over the place and they say the same thing pretty much...
Is your controller located in application/core?
Well yes it is. I can't seem to get passed this hump!
This is the code within My_Staffcontroller.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_staffcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
$loggedin = $this->session->userdata('loggedin');
if(!isset($loggedin) || $loggedin != TRUE);
{
die($this->load->view('denied'));
}
}
}
I know this is user error as this is only my second day with CodeIgniter but I can't seem to find proper workaround for this?
I have tried this tutorial and still nothing and also this
Even following this video has me stuck on the session part.
And I just can not get this to work.
Remember Linux is case-sensative whereas Windows is case-insensative.
place you're MY_Staffcontroller inside application/core/MY_Controller.php file
Your MY_Controller.php file should look like this (minus all you're other functions, this is a minimal example)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
}
class MY_Staffcontroller extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function sayHello()
{
echo "Hello, I am a function within MY_Staffcontroller.php";
}
}
Example
This will be located in /application/controllers directory
Basically any protected and public functions located in either MY_Controller OR MY_Staffcontroller will be accessible from derived controllers that extend the extended controller. In this case it would be MY_Staffcontroller
class Public_Staff_Controller extends MY_Staffcontroller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->sayHello();
}
}
/* end of file /application/core/MY_Controller.php */

Categories