CodeIgniter Forums
Avoid validate session in each method of controller - Printable Version

+- CodeIgniter Forums (
+-- Forum: Archived Discussions (
+--- Forum: Archived Development & Programming (
+--- Thread: Avoid validate session in each method of controller (/thread-60580.html)

Avoid validate session in each method of controller - El Forum - 05-01-2014

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:


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.

class Sede extends CI_Controller{

public function __construct(){

function index(){
if (!$this->native_session->get('IdUsuario')){
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();


Avoid validate session in each method of controller - El Forum - 05-01-2014

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:

* A controller specific my web applications that will force
* authentication before granting access
class My_Controller extends CI_Controller {
function __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.