views:

143

answers:

5

I might be nitpicking, but is it better to do this:

if ($loggedin) {
    // normal process
}
else {
    header('Location: login.php');
}

Or this:

if (!$loggedin) {
    header('Location: login.php');
    exit();
}
// normal process

Or does it just not matter?

+5  A: 

I prefer the second style, since "//normal process" is likely a long piece of code, so the last } (from the else branch) might be a bit confusing.

ammoQ
+5  A: 

I prefer the 2nd one because that way "normal process" is not already 1 indentation level deep because of a simple check. I think PHP probably optimizes this away so that performance is irrelevant, so at that point it's a matter of readability and the 2nd one makes more sense to me ("Not logged in, redirect, exit") over wrapping all your logic in one huge IF.

Paolo Bergantino
+1  A: 

It really doesn't make any difference. In my personal opinion the second branch is easier to understand, because you do not have to scroll to the end to see what is happening when the user is not logged in.

Hippo
A: 

You should always use exit or die after redirecting to avoid further code being executed.

But besides that I also prefer the second since $loggedin is a precondition for your “normal process”.

Gumbo
A: 

Definitely the second. It reads better and works better for the rest of your code.

Hans