开发者

Best place to check if logged-in -- Codeigniter/PHP

Currently I use the following for checking is a user is logged in:

function only_a_loggedin_user_can_do_this()
{
    if($user_is_logged_in)
    {
       do something that only users can do
    }
    else
    {
        red开发者_如何学JAVAirect('/login_page/');
    }
}

but if my controller has many functions is a bit of a pain in the arse to write or make changes.

Whats the best way to achieve what I want but in a more simplistic way that is easier to update. I was thinking of the below,

function check_if_logged_in()
{
    if($user_is_logged_in)
    {
       function only_a_logged-in_user_can_do_this()
       {
       }

       function or_this()
       {
       }

    }
    else
    {
        redirect('/login_page/');
    }
}

but would that mean adding adding something to the URI string, eg

www.example.com/index.php/check_if_logged_in/only_a_logged-in_user_can_do_this/

Whats the best way to implement this?


   function only_a_logged-in_user_can_do_this()
   {
     check_if_logged_in();
     // do stuff

   }

   function or_this()
   {
     check_if_logged_in();
     // do stuff
   }

   function check_if_logged_in()
   {
     if( ! $user_is_logged_in)
     {
       redirect('/login_page/');
     }
   }

This probably simpler because you need not repeat the if for each function you are protecting. you just need do the method.

Of course if you need to protect all methods, you can do it in the constructor.

Class Blah extends CI_Controller
{

  function __construct()
  {
    check_if_logged_in();
  }

   function check_if_logged_in()
   {
     if( ! $user_is_logged_in)
     {
       redirect('/login_page/');
     }
   }
}


Not sure if this is the best way or not but it seemed to work for the project:

I had a controller and in the constructor did my login check. If it was successful then the 'action' method would be allowed to be performed, otherwise redirect.

class Admin extends MY_Controller {

    function Admin()
    {
        $this->__construct();
    }

    function __construct() {
        parent::__construct();

        //perform check 
        //if allowed then automatically continue
        //else do a redirect
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜