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

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

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>
}

Codeigniter userdata login session to make it available for all model/controller functions

I have this login function in controller :
public function members() {
if($this->session->userdata('is_logged_in')){
redirect('pag/index');
}else{
redirect('main/restricted');
}
My index will load, but my model/controllers functions won't load because of the user session.
I read about doing a MY_controller in the core, mine looks like this :
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'/libraries/HttpResponse.php');
class MY_Controller extends CI_Controller {
private $_additional_css = array();
private $_additional_js = array();
function __construct() {
parent::__construct();
}
public function is_logged_in($user=true)
{
$user = $this->session->userdata('user_data');
return isset($user);
}
}
But it wont work, any idea?
make changes in login controller function :-
pass exact session parameter that you set in your session
public function is_logged_in('user_data')
{
$user = $this->session->userdata('user_data');
return $user;
}
after this make changes in MY_conroller:- pass variable parameter in is_logged_in function
public function is_logged_in($user_data)
{
$user = $this->session->userdata($user_data);
return $user;
}
Enable hook in config.php
$config['enable_hooks'] = TRUE;
write following code into application/config/hooks.php file
$hook['post_controller'] = array(
'class' => 'MyClass',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'controller',
'params' => ''
);
and last step is Create myclass.php controller in your controller folder
class myclass extends CI_Controller
{
function myfunction()
{
if($this->session->userdata('is_logged_in'))
{
redirect('pag/index');
}
else
{
redirect('main/restricted');
}
}
}

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.

How to block acces for all methods to Admin Controller

I need to block access to other methods in Admin controller if admin is not logged in.For example if I write base_url/administration/show/index I can access without login in system
Pleez help,Thx
Login Controller:
class Login extends CI_Controller{
function __construct(){
parent::__construct();
}
public function index(){
// Load our view to be displayed
// to the user
$this->load->view('admin/authentification_view');
}
public function process()
{
// Load the model
$this->load->model('login_model');
// Validate the user can login
$result = $this->login_model->validate();
// Now we verify the result
if(! $result){
// If user did not validate, then show them login page again
$this->index();
}else{
// If user did validate,
// Send them to members area
redirect('administration/show/index');
}
}
}
Login Model
class Login_model extends CI_Model{
function __construct(){
parent::__construct();
}
public function validate()
{
$login = $this->security->xss_clean($this->input->post('login'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->where('login', $login);
$this->db->where('password', $password);
$query = $this->db->get('admin_details');
if($query->num_rows == 1)
{
// Creare date sesiuni
$row = $query->row();
$data = array(
'id' => $row->id,
'login' => $row->login,
'password' => $row->password,
'validated' => true
);
$this->session->set_userdata($data);
return true;
}
return false;
}
}
Administration Controller
class Administration extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('administration_page_model');
$this->load->model('crud');
$this->load->helper('url');
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
public function show($admin_page)
{
$data = array();
$data["news"] = $this->administration_model->allNews();
switch($admin_page)
{
case 'index':
$name = 'admin/index';
$this->display_lib->admin_page($data,$name);
break;
case 'add_news':
$name = 'admin/addnews';
$this->display_lib->admin_page($data,$name);
break;
case 'all':
$name = 'admin/all';
$this->display_lib->admin_page($data,$name);
break;
}
}
}
The easiest seperation would be to define the following classes in application/core:
Base_Controller extends CI_Controller
- some basic stuff, setting vars etc
Admin_Controller extends Base_Controller
- integrate your logic/library that determines a user as an admin
- for example: If(!isAdmin) -> redirect to login
Auth_Controller extends Base_Controller
- for example: If(!isLoggedIn) -> redirect to login
Front_Controller extends Base_Controller
- no need for auth or admin, then use this one
You can simply put in the constructor of any admin controller :
function __construct()
{
parent::__construct();
if(!$this->session->userdata('validated')) redirect('login');
}
You can also check out Ion_Auth plugin (it manages authentifications, accounts, etc). You will just need to call :
function __construct()
{
parent::__construct();
if(!$this->ion_auth->logged_in()) redirect('login');
}
Create a helper function check_login() to cjeck if user is logged in and the call this helper in your constructor for every class where you need to check login .
public function check_login(){
$ci = & get_instance();
if(!isset($ci->session->userdata['validated']))
{
//do what u want if user is not loogged in
//for example redirect('home page url');
}
}
Now in every constructor just add this line
check_login();
to learn more about helper functions see
http://ellislab.com/codeigniter/user-guide/general/helpers.html

Calling a Controller function in another Controller in CodeIgniter

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

Categories