Welcome Guest, Not a member yet? Register   Sign In
Simple Question - Best way to check for login status
#1

[eluser]PoetaWD[/eluser]
Hello All,

I am very new to PHP and programming...

I am developing a application where to enter a page the system checks if the user is logged in or not...

My question is not regarding that...

The question I have is about how is the best way of doing it...

Is it safe to do like this:

Code:
function check_login
{
   if(!$this->dx_auth->is_logged_in())
   {
      redirect('welcome');
   }
}

function index
{
   $this->check_login();
  
   //... THE REST OF MY CODE

}

The way I AM DOING IS THIS,

Code:
function index
{
   if(!$this->dx_auth->is_logged_in())
   {
      //... THE REST OF MY CODE
   }
   else
   {
      redirect('welcome');
   }
}

I am sure this way is safe... All I want to know, to cleanup my code is if that other way is also safe.... or users can prevent not to be redirected....

Thanks in advance

Gabriel
#2

[eluser]Prophet[/eluser]
Either way is fine. The benefit of using method #1 is that if you change the auth library or need to add some extra code, you only need to change the one function. If the same happens with method #2, you may find that you need to change not only the index() function, but also any others you may have within that controller.

Edit: I forgot to mention that the benefit of using method #2 is that you are not limited to the one check_login function. Sometimes you may want to redirect to a different page, in which case method #2 is the best choice.
#3

[eluser]Isern Palaus[/eluser]
Code:
function index()
{
   if($this->dx_auth->is_logged_in())
   {
      redirect('backend');
   }

   // REST OF THE CODE
}

Is another way Smile and you can redirect wherever you want! Big Grin
#4

[eluser]umefarooq[/eluser]
read this article also it can help you more to solve you problem you can create a common controller to check user login or not, no need to put in each and every controller

http://philsturgeon.co.uk/news/2010/02/C...ing-it-DRY
#5

[eluser]PoetaWD[/eluser]
Ok GUYS !

Thanks for the quick replies !

I am glad to know that it is safa either way,,,,

I was just thinking if someone is able to not be redirected someway...




Theme © iAndrew 2016 - Forum software by © MyBB