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

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.

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.

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.

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

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();
}
}

Authentication CodeIgniter views

I have a login helper in my CodeIgniter project.
In every constructor of a controller I call a function to check if the user is logged in.
However when calling a function(getSetup) when logged out the login_view appears but also the other view db_manage for example. But I don't want to show content when not logged in.. How to fix this ?
Thanks
function __construct() {
parent::__construct();
if (!is_logged_in()) {
$this->load->view('login_view');
}
}
public function getSetup() {
$this->load->view("db_manage");
}
this way:
function __construct() {
parent::__construct();
if (!is_logged_in()) {
echo $this->load->view('login_view', null, TRUE);
exit();
}
}
yes, you can't exit in the c'tor that will stop Codeigniter from doing its render process from the output buffer. You can't really do this from the c'tor, its not really what the c'tor is for, its meant for setting up the class variables..
you should check the logged in from the method, and return the login view from there.
class My_Controller {
function ensureLoggedIn() {
if(!is_logged_in()) {
$this->load->view('login_view');
return False;
}
return True;
}
function getSetup() {
if(!$this->ensureLoggedIn())
return;
.... rest of method ...
}
}
#egig - whats the point in using a framework if your going to bypass the stack?!

Codeigniter extends core class

I want to have class that checks login on all controllers that I specified.
Codeigniter version is 2.1.0 and I have php 5.3.10
Hier is how I would set it up:
I look at https://www.codeigniter.com/user_guide/general/core_classes.html
and I set it up like this:
in the /application/core/MY_Main.php
class MY_Main extends CI_Controller {
function __construct()
{
parent::__construct();
}
}
In my controller I have welcome.php
?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Main {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('welcome_message');
}
}
So if I place login check in MY-Main it should get work, but I cant get it work anyone???
I needed to add the following code to /application/config/config.php before I got the extenson of core classes working as described in the CI manual.
Code taken from here http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY
function __autoload($class)
{
if(strpos($class, 'CI_') !== 0)
{
#include_once( APPPATH . 'core/'. $class . EXT );
}
}
You logic is correct, that should work. It's exactly what I do on all my codeigniter sites. My code is a bit more complex as my login check is being called from a library (so I have to call $CI =& get_instance(); and then $CI in place of $this) but something like below should work for you. logged_in is just a name given to an item of session data set when the user logs in.
class MY_Main extends CI_Controller {
function __construct()
{
parent::__construct();
$session_data = $this->session->all_userdata();
if(!isset($session_data['logged_in']))
redirect('/login');
}
}
In regards to your comment above (http 500), not really sure what's going on there. The code you have pasted shouldnt be throwing errors like that so something else is probably going on. Try turning on codeigniters built in logging functionality.
http://codeigniter.com/user_guide/general/errors.html
You should create a library class and put it inside your library folder and load it as auto_load or inside your controllers.
create functions inside your library for example:
/**
*
* #return boolean check if a user is logged in or not
*/
function notLogin()
{
if (!$this->is_logged_in()){
//echo "pelase <a href='login'><b>login</b></a> to continue ";
redirect('home/login','refresh'); exit;
}
return true;
}
and call it inside your controller constructor or any functions you want like this:
class Main extends CI_Controller
{
private $POST = array();
private $ci_form;
function __construct()
{
parent::__construct();
//check if user is logged in or not
$this->m_auth->notLogin();
$this->load->library('form_validation');
$this->load->library('ajax_pagination');
}
}
It some time happens because of database connection.
Please check if your database :
has been selected by turning-on error reporting from your Cpanel error log.
user has been added to your database.

Categories