PHP - used __construct() to check if there is a session - php

I need to resolve a doubt, I leave the details.
I have a class that has multiple related queries to the database with user data, to access these methods need to verify that the user is logged in, and I do it using php initializer "__construct ()" methods, specify there if the user logged on.
<?php
class User()
{
public function __construct() {
if ( !isset($_SESSION['user']) ) {
$data = array(
'response' => false,
'message' => 'You must login to access this page'.
);
echo json_encode($data);
}
}
public function index() {
// The user can access if you are logged
}
public function edit_profile() {
// The user can not access if you have not logged
}
public function save_profile_data() {
// The user can not access if you have not logged
}
}
?>
My questions:
Use the __construct() is a good optimal choice resource-intensive?
The __construct() is safe to use and prevent the user to access other methods that have not specified whether there is coded session variable.
Ie if a user calls the edit_profile() method, and this method does not have the code to check for the session, but I have specified in the __construct(), the user can access this method?
I hope you can help me, I would greatly appreciate.

I suggest you to create your own library file in library folder
Here is the class file
class Authenticate {
var $table;
public function __construct()
{
$this->ci =& get_instance();
}
public function is_logged_in()
{
$sessionid = $this->ci->session->userdata('moderId');
if($sessionid)
{
return isset($sessionid);
}
else if(!$sessionid) {
redirect(base_url() . 'moderator');
}
}
}
And in your controller,use this function.if you put this function in the constructor of the controller,then it wil be available to all methods
Controller
class B2bcategory extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('moderator/b2bcategory_model');
$this->authenticate->is_logged_in();
}
}

Related

Redirecting to a certain controller function if validation failed in codeigniter

I am trying to redirect to controller index if not authorized the access to other functions within same controller. According to my coding it is looking like infinite loop. Please help me to do that.
class Customer_Dashboard extends CI_Controller {
public function __construct() {
$method= $this->router->fetch_method();
if ($this->session->userdata("cus_sel_comp")) {
}else{
if($method !="index"){
redirect(base_url()."customer_dashboard");exit;
}
}
}
public function index() {
// Here do some operations and let the user to select company and update the "cus_sel_comp" session variable. After set that session user can access the other controller functions.
}
public function other_function1() {
}
public function other_function2() {
}
}
My coding is as above. I need to do this using same controller. Problem is if that session not set there is a infinite loop.
Instead of redirecting return index function. See the code below
if($method !="index"){
return $this->index();
}
You are calling the same function and redirecting it to same method.
class Customer_Dashboard extends CI_Controller {
public function __construct() {
$method= $this->router->fetch_method();
if ($this->session->userdata("cus_sel_comp")) {
}else{
if($method !="index"){
redirect(base_url()."Customer_Dashboard/index"); // Redirect it to index if other method is invoked.
}
}
}
public function index() {
// Here do some operations and let the user to select company and update the "cus_sel_comp" session variable. After set that session user can access the other controller functions.
}
public function other_function1() {
}
public function other_function2() {
}
}
Also dont use base_url() instead of that define an path in config
base_url() has many other entries present which are un-necessarily called.

Codeigniter view executed twice when calling a function from constructor

I followed a tutorial on how to set up a login system for php apps in codeigniter. The logic when the user has session data is working great, but I have a problem when the user isn't logged in (f.ex. refreshes the page after a while). The view of "not_logged_in" gets executed twice when I were to call for the functin from constructor.
The following code works, but it means I gotta add the code for every function I add after.
class App extends CI_Controller {
function __construct()
{
parent::__construct();
}
private function logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if (isset($is_logged_in) OR $is_logged_in)
{
return TRUE;
}
else
{
$data['title'] = 'Chyba přihlášení';
$data['main_content'] = 'not_logged_in';
$this->load->view('includes/template', $data);
return FALSE;
}
}
function index()
{
if($this->logged_in())
{
$data['title'] = 'APLIKACE';
$data['main_content'] = 'app_view';
$data['userid'] = $this->session->userdata('userid'); //get userid from session
$this->session->unset_userdata('userid'); //destroy the data
$this->load->view('includes/template' , $data);
}
}
function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
Now the real question, how would I go about putting the whole logic into a constructor without having to check for it in every function?
Make APPPATH.'core/MY_Controller.php' file and put authentication logic in constructor there. Than extend that class from every controller (you need auth logic).
class MY_Controller extends CI_Controller
{
public function __construct();
{
parent::__construct();
$this->check_login();
}
protected function check_login()
{
$is_logged_in = $this->session->userdata('is_logged_in');
//here should be *AND* instead *OR* logic
if (isset($is_logged_in) && !empty($is_logged_in))
{
return TRUE;
}
else
{
redirect('login/index');
exit();
}
}
}
Login.php controller:
class Login extends CI_Controller//NOT extending MY_Controller to avoid infinite loop
{
public function __construct();
{
parent::__construct();
}
public function index()
{
//here is login view
//and logic of preserving session
//with redirect to 'app/index' after successful login
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
App.php controller:
class App extends MY_Controller//extending MY_Controller to check login status
{
public function __construct();
{
parent::__construct();
}
public function index()
{
//here is app dashboard view
}
public function statistics()
{
//here is some other method that requires logged in user
}
}
I also would recommend you to check Ion_auth authentication system to see if suitable for you.

is_logged_in check on every page

I am using CodeIgniter. I have a controller named abc and i has functions named index,a,bandc.
www.example.com/abc/
I want that user can only access the area he is logged in.
www.example.com/abc/ //if loggged in else back to homepage
or
www.example.com/abc/a/ //if loggged in else back to homepage
Now to check login. I use:
if($this->auth->is_logged_in()) { .. } else { redirect('/'); }
on every function individually.
Is there any other way to do so ??
I think you can do this by overriding the constructor and call your function in it.
<?php
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
// check login
}
}
?>
For a particular controller you can put your if check in the constructor of the controller so that when any method of the controller is called it will pass through your if check
class Abc extends CI_Controller {
public function __construct()
{
parent::__construct();
//your if goes here
}
}
And if you want to check the user is logged in or not in the whole application you can use the constructor method __construct() of CI_Controller so it will be validated when user access any of the controllers within your application
class CI_Controller {
private static $instance;
/**
* Constructor
*/
public function __construct()
{
//your if goes here
}
}

How to exit codeigniter without die() in __construct() function of controller?

I have a controller where in the constructor function, I want to check if the user is logged in or not. If not, I want an error message to be displayed, and for the script to exit without running any other function in the controller. This controller will only be called by ajax so the error would be displayed via JSON and then the javascript on the client will display it to the user.
How can I do this? If I did this:
function __construct()
{
if (! $this->loggedIn() )
{
echo json_encode( array('error'=> true) );
die;
}
}
I don't think the message would be displayed because codeigniter uses output buffering. Any ideas?
i understood that your problem is the client expects for a json type of response, so two options to use:
public function __construct(){
$_bad_login_msg = 'please try again' ;
parent::__construct();
if(!userLoggedIn()){
$this->output
->set_content_type('application/json')
->set_output(json_encode($_bad_login_msg));
//or just use
// echo json_encode($_bad_login_msg);
die;
}
}
http://codeigniter.com/user_guide/libraries/output.html
you won't have any buffering problems, the buffer contents will be sent to the client after the die...
The best way is to redirect the user to login page.
As mentioned here : https://stackoverflow.com/a/10399199/876117
public function __construct(){
parent::__construct();
if(!userLoggedIn())
$this->load->view('promptlogin');
$this->output->_display();
exit();
}
public function index(){
// one will never reach here unless he is logged in
$this->load->view('actualcontent');
}
I'm pretty sure you can just use something like this:
function __construct()
{
if (! $this->loggedIn() )
{
exit('Please login before visiting this page');
}
}
MY_Controller is your top level/parent controller so its all done in there because every other controller will extend it. So if you have an auth controller(which extends MY_Controller) you will have access to its logic.
So MY_Controller
class MY_Controller extends CI_Controller{
protected $_user;
public function __construct(){
parent::__construct();
$this->_user = $this->session->userdata('uid')
? find_a_user : NULL;
// if a session of user_id exists and is found in DB
// we have a live user
}
}
Auth
class Auth extends MY_Controller{
public function __construct(){
parent::__construct();
// we now have access to $this->_user
if($this->_user !== NULL) // we have active user
}
}
I think you should use flashdata and redirect to a controller with it. Then you can control if any flashdata comes in session, after that write it in view.

How i can use a __construct function in my other CodeIgniter controller

I have a controller called member within this a construct function
function __construct()
{
parent::Controller();
$this->is_logged_in();
}
I want to check in my other controller that user is logged in how I can use this function in my other controller called profile and others
This is my First project with CodeIgniter
Your authentication checks should be in a library:
The is an excerpt from a basic codigniter authentcation script:
class Site_sentry
{
function Site_sentry()
{
$this->obj =& get_instance();
}
function is_logged_in()
{
if ($this->obj->session)
{
if ($this->obj->session->userdata('session_logged_in'))
{
return TRUE;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
}
function login_routine()
{
//do login here (enter into session)
}
}
This library is stored in application/libraries under a filename named after its class with the .php suffix.
Then you can either add this to your autoload config file application/conig/config.php:
$autoload['libraries'] = array('database', 'site_sentry', 'session');
or load it manually in each controller:
$this->load->library('Site_sentry);
Then you can check your session from within controllers, like so:
class Class extends Controller{
function Class()
{
parent::Controller();
if( $this->site_sentry->is_logged_in() == FALSE){
redirect('managerlogin/');
}
}
}
Also check this documentation page http://codeigniter.com/user_guide/libraries/sessions.html; of particular interest is the storing the session into the database section.
I don't think that doing it with the class is the best idea. If the user is logged in, you should check for a flag (value or whatever) inside the session, so you don't need to work with the other controller.
The advantage would be that the session can be accessed more easily and it is the more common approach.
Example with session:
class SomeClass extends Controller {
function __construct()
{
parent::Controller();
$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)
{
redirect('login');
}
}

Categories