<?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.
Related
After the user logs in, I set the variable is_logged_in=true, but in some other controller how can I check is_logged_in is true in codeigniter?
Here is my login code:
public login_con extends CI_Controller
{
public function login()
{
is_logged_in=true;
}
}
I want to check this is_logged_in in another controller so how can i write code for that?
Session is best solution for this. You can read codeignitor session
// set value in session
$this->session->set_userdata('is_logged_in', true);
To get in other controller
$is_logged_in = $this->session->userdata('is_logged_in');
Please also make sure you have loaded session library.
$this->load->library('session');
First thing autoload applications/config/autoload.php, to add session library
$autoload['libraries'] = array('session');
This will include session on every page.
Now your controller file
controller1
public login_con extends CI_Controller
{
public function login()
{
//here you set session like that
$data['is_logged_in'] = TRUE;
$this->session->set_userdata($data);
}
}
Here you get your is_logged_in session on other controller
controller2
public your_con extends CI_Controller
{
public function your_function()
{
//here you get session like that
if($this->session->userdata("is_logged_in"))
{
// your code here
}
}
}
How to set user previleges in array using codeigniter. for example i have a controller name prospect and its method. I have to check if the logged in user have permission to access these controller methods. how to check anyone please give me advise on this.
You can set permission to access these controller/methods in constructor of the controller.
See the example:
class Admin extends CI_Controller {
function __construct()
{
parent::__construct();
$session_user = $this->session->userdata('session_array');
$method = $this->router->fetch_method();
if(empty($session_user) && $method != 'login'){
redirect('admin/login');
}
}
public function login(){
// Login method
}
public function index(){
// home page method
}
}
Here you can only access the function login from the controller admin. If you access the other functions it redirects to login method of admin controller if the session is not present.
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;
}
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.
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();
}
}