• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
function which gets invoked on each method call of controller

[eluser]arslan ali[/eluser]
I am writing the feature which allows end user to bypass login mechanism by the help of cookies.

For a session to get initialized, if a cookie is set, i need a function which gets invoked on each time page gets refresh, so authentication can be performed

[eluser]Phil Sturgeon[/eluser]
Use a post_controller_constructor hook for this, or at least thats what I do. For an example:


<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files.  Please see the user guide for info:
|    http://www.ellislab.com/codeigniter/user-guide/general/hooks.html

$hook['post_controller_constructor'][] = array(
    'function' => 'grantAccess',
    'filename' => 'grantAccess.php',
    'filepath' => 'hooks',



<?php   if (!defined('BASEPATH')) exit('No direct script access allowed');

function grantAccess()
    $CI =& get_instance();

    if($CI->config->item('require_login') === FALSE):
    // Get some page request details
    $directory = $CI->uri->router->directory;
    $class = $CI->uri->router->class;
    $method = $CI->uri->router->method;    
    // if no-one is logged in
        // unless they are on an allowed page, prep for login!
        if(!in_array($class.'/'.$method, $CI->config->item('allowed_pages'))):
            // Clear all sessions
            // Store current URI as a string to be redirected to on login
            $CI->session->set_userdata('loginRed', $_SERVER['HTTP_REFERER']);//$CI->uri->uri_string());

    // If user is logged in
        // If an admin panel, check the user is an moderator or above admin
        if($directory == 'admincp/'):        
            if(!$CI->permission->check('mod') && !in_array($directory.$class.'/'.$method, $CI->config->item('allowed_pages'))):


That hook is a little overcomplicated, but you can simply make an empty function called grantAccess then do your if(logged in) code in that. Redirect if false, leave it alone if true. Dont bother returning values,t hey wont be picked up anywhere.

If you only want to invoke the function in a single controller you don't need to use the slick hooks device pyro has suggested - just put your function in the controller constructor, which, as you know, is called on every method of a controller.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.