Welcome Guest, Not a member yet? Register   Sign In
Avoid validate session in each method of controller
#1

[eluser]Unknown[/eluser]
Hi friends, first of all I apologize for my English writing is not very good.

I recently started using CodeIgniter. I have used native sessions, my problem is I'm trying to avoid any page to load if there is no active session, I've been doing this validation in the index and effectively work, but when the user don't have an active session, the controller redirect to login. Now have been trying to access from the url both the controller and the method, and I realize that doesn't validate the session, my alternative was doing the same validation that I do in the index, in each one of the methods of controller, but I'm not convinced that alternative, I think should there be a general way to do it at the controller level.

I would ask you please suggest me another way to do this or some reference where I can read more about it.

For example when I access as follows:


localhost/inventariomptci/sede/obtener_sede_por_id

then, show me the contents of the page, with mistakes because there isn't session, I would want to redirect to login,

Below I show you some of my code,

I thanked you for any help you can give me.

<?php
class Sede extends CI_Controller{

public function __construct(){
parent::__construct();
$this->load->helper('url');
//$this->load->library('native_session');
$this->load->model('sede_model');
}

function index(){
if (!$this->native_session->get('IdUsuario')){
//$this->load->view("acceso_usuario/login");
redirect('acceso_usuario', 'refresh');
} else {
$bread_crumbs = $_POST["rutaMenuBreadCrumbs"];
$data["titulo"] = "Sede"; // parametro
$data["subtitulo"] = ""; // parametro
$data["bread_crumbs"] = $bread_crumbs; // parametro

$contenido_vista = $this->load->view("sede/sede",$data, TRUE);
print $contenido_vista;
}
}

public function obtener_sede_por_id(){

$id = $_POST["idSede"];
$array_sede = $this->sede_model->obtener_sede_por_id($id);

$arreglo = array();

.....
#2

[eluser]sneakyimp[/eluser]
I recommend that you write a class to extend CI_Controller and in the constructor of this class, you put your session check. Something like this:

Code:
/**
* A controller specific my web applications that will force
* authentication before granting access
*/
class My_Controller extends CI_Controller {
function __construct() {
  parent::__construct();
  
  // check login here
  if (!$this->native_session->get(‘IdUsuario’)){
   redirect(‘acceso_usuario’, ‘refresh’);
  }
} // __construct()

} // class My_Controller

Then instead of having your controllers extend CI_Controller, have them extend My_Controller. You may have a bit of trouble getting code igniter to find your class. You may also need to work on that a little to make sure you've loaded your native_session module.




Theme © iAndrew 2016 - Forum software by © MyBB