Calling a Controller function in another Controller in CodeIgniter - php

I have a controller "user" in my codeigniter application. This controller has a function called logged_user_only():
public function logged_user_only()
{
$is_logged = $this -> is_logged();
if( $is_logged === FALSE)
{
redirect('user/login_form');
}
}
As this function calls another function called is_logged(), which just checks if the session is set, if yes it returns true, else returns false.
Now if i place this function in the begining of any function within same controller, it will check if the user is not logged, it will redirect to login_form otherwise continue. This works fine.
For example,
public function show_home()
{
$this -> logged_user_only();
$this->load->view('show_home_view');
}
Now I would like to call this logged_user_only() function in a function of another controller to check if the user is logged in or not?
PS. If this can not be done, or is not recommended, where should i place this function to access in multiple controllers? Thanks.

Why not extend the controllers so the login method is within a MY controller (within the core folder of your application) and all your other controllers extend this. For example you could have:
class MY_Controller extends CI_Controller {
public function is_logged()
{
//Your code here
}
}
and your main controllers could then extend this as follows:
class Home_Controller extends MY_Controller {
public function show_home()
{
if (!$this->is_logged()) {
return false;
}
}
}
For further information visit: Creating Core System Classes
New link is here:
https://www.codeigniter.com/user_guide/general/core_classes.html?highlight=core%20classes

Calling a controller from another is not possible with CI and not recommended.
Either move your logged_user_only into a helper or even better a core controller that you extend all of your controllers from (MY_Controller) see http://codeigniter.com/wiki/MY_Controller_-_how_to_extend_the_CI_Controller/

just load user controller as library from your controller
function __construct(){
parent::__construct();
$this->load->library('../controllers/user');
}
Now, call this function of user controller any where in your controller,
$this->user->logged_user_only();

Function login in Controller Login
$data =array('username' => $this->input->post('username'), 'password' => $this->input >post('password')) $query = $this->db->get_where('usertable',$data)
if ($query->num_rows() == 1) {
$data = array(
'username' => $this->input->post('username'),
'logged_in' => TRUE,
'role' => "user");
$this->session->set_userdata($data);
redirect('home');
}
Function Construct in Controller user
if ($this->session->userdata('logged_in') == TRUE && $this->session->userdata('role') == "user") {} else {redirect('home');}

Related

How to redirect from view to controller in codeigniter?

In my header view I wrote this code:
<?php
if($this->session->userdata('logged_in')) {
$query = $this->db->get_where('instructors', array('id' => $this->session->userdata('id')));
$insdatacheck = $query->row_array();
if($insdatacheck['name'] == '') {
redirect(base_url().'user/continueregistration');
} else { ?>
<script type="text/javascript">alert('test');</script>
<?php
}
}
?>
But it does not redirect to the following page. However, if I write this in the controller, it works properly. I wrote it in header view because I want to check it in every page where enters the user. How can I improve it and write in a proper way? Thanks in advance
I think instead of your header you should put your check inside your controller constructor.
class Test extends CI_Controller {
function __construct() {
parent::__construct();
// if not logged-in redirect to login page
if ($this->session->userdata('logged_in') == false) {
redirect('login'); // where you want to redirect
}
}
}
Another option is to create a base controller. Place the function in the base controller and then inherit from this.
To achieve this in CodeIgniter, create a file called MY_Controller.php in the libraries folder of your application.
class MY_Controller extends Controller
{
public function __construct()
{
parent::__construct();
}
public function is_logged_in()
{
$user = $this->session->userdata('user_data');
return isset($user);
}
}
Then make your controller inherit from this base controller.
class X extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function do_something()
{
if ($this->is_logged_in())
{
// User is logged in. Do something.
}
}
}
First create session in the controller only,
Then we access session in any page,
$this->load->library('session');
$user=$this->session->userdata('logged_in');
if (!isset($user)) {
redirect(base_url().'user/continueregistration');
}
else {
<script type="text/javascript">alert('test');</script>
}

have a variable available in all Yii views

I would like to have a variable $user_profile available in most of my view files, without me having to create the variable in each controller file. At the moment I have things working but I was wondering if there is a better solution
I have some code to populate a variable
$user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
Then a parent class
class Controller extends CController {
public function getUserProfile()
{
$user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
}
}
Then I have all other controllers inheriting the Controller class, for example
class DashboardController extends Controller
{
public function actionIndex()
{
$user_profile = parent::getUserProfile();
$this->render('index', array('user_profile' => $user_profile));
}
}
Then finally in the view file I can simply access the $user_profile variable.
Create class field in your base controller class:
class Controller extends CController {
public $user_profile;
public function init()
{
parent::init();
$this->user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile;
}
}
Don't need to pass it directly to view:
public function actionIndex()
{
$this->render('index');
}
Then you can access it in view using $this:
// index.php
var_dump($this->user_profile);
You already have a getter defined, so you can use $this->userProfile from both, your controllers and your views. I'd only add a caching logic to avoid multiple queries to the database:
class Controller extends CController
{
protected $_userProfile=false;
/*
* #return mixed a User object or null if user not found or guest user
*/
public function getUserProfile()
{
if($this->_userProfile===false) {
$user = YumUser::model()->findByPk(Yii::app()->user->id);
$this->_userProfile = $user===null ? null : $user->profile;
}
return $this->_userProfile;
}
For user profile info, I populate a small number of variables upon login using setState to store the data.
In your UserIdentity class after a successful authentication, you can store data similar to this:
$userRecord = User::model()->find("user_name='".$this->username."'");
$this->setState('display_name',
(isset($userRecord->first_name)) ?
$userRecord->first_name : $userRecord->user_name);
Then in any view, it can be accessed like:
echo (isset(Yii::app()->user->display_name) ?
Yii::app()->user->display_name : 'Guest');

echo username from session without defining in every controller [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
echo user in view from sessions code igniter
I don't want to define and store the user in every controller and then pass it to the view.
Here's my controller:
Login controller:
class LoginController extends CI_Controller {
function index(){
$new['main_content'] = 'loginView';
$this->load->view('loginTemplate/template', $new);
}
function verifyUser(){
//getting parameters from view
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$this->load->model('loginModel');
$query = $this->loginModel->validate($data);
if ($query){
//if the user c validated data variable is created becx we want to put username in session
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('sessionController/dashboard_area');
}else{
$this->index();
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
?>
My controller, which I've stored in core folder, so now every controller now extends this controller. I think this controller can be customize so I can access the user in every view page which extended this controller:
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$this->is_logged_in();
}
function dashboard_area(){
$data['main_content'] = 'dashboardView';
$this->load->view('dashboardTemplate/template', $data);
}
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.';
redirect('loginController');
}
}
}
?>
Here is my simple one member controller which extended the above controller:
Here in index function I am storing the username and then pass into the view which I don't want to do:
class CategoryController extends MY_Controller {
function index(){
$data['main_content'] = 'categoryView';
$username= $this->session->userdata('username');
$data['username']=$username;
$this->load->view('dashboardTemplate/template',$data);
}
You can just call $this->session->userdata('username') in your view.
It is stored in the session, so you do not have to pass it to the views from the controller.
UPDATE PER COMMENT;
if you want to load a view depending on the base controller (eg user), I would use a template library and set the template to use in the construct of the base controller.
For example (using this template library);
class MY_User extends CI_Controller {
public __construct() {
parent::__construct();
$this->is_logged_in();
$this->template->set_template('user');
}
}
class MY_Admin extends CI_Controller {
public __construct() {
parent::__construct();
$this->is_logged_in();
$this->template->set_template('admin');
}
}

It is right my auth in codeIgniter

if($this->session->userdata('admin') === false)
{
$this->load->helper('form');
$data['content'] = $this->load->view(ADMIN.'login', null, true);
$this->load->view(ADMIN.'layout', $data);
return false;
}
so this is the code in the controller admin, function constructor.
It checks if the admin session is true, the question is how bad is this type of authorization, by checking it in the constructor? Because the user can't use other functions in this controller before he didn't pass the constructor.
Make a library, and do all checking like this inside. After loading this library into your Controller, then you can use your - for example isAdmin(); - function in any part of your Controller's code.
Class AdminPanel extends CI_Controller{
function __construct(){
if($this->session->userdata('admin') === false)
redirect(site_url());
}
}
}

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