Question

I've seen both of these in scripts and was wondering from strictly a security standpoint if one outweighs the other? Is it better to include the secure page content within an IF statement?

if(!login_check($mysqli)) {
    header("Location: index.php"); 
    exit;
}

//Secure Page Content.

Or...

if (login_check($mysqli)) {

    //Secure Page Content.

} else { 
    header("Location: index.php");
}
exit;
Was it helpful?

Solution

Strictly from a security point, i'd say no difference. That being said. The first is much clearer to read. If the page content is more than a screen you've lost track of where the conditional ends. This could lead to making an error somewhere in the code where another else is executed and the page becomes open.

Supplying an exit directly after the check eliminates a human error becoming a security hole in the rest of the code, and in my opinion is much easier to digest and won't lead to a troubleshooting issue in the future.

OTHER TIPS

This can be reduced to the question: do you accept multiple return points?

Case 1:

function (a, b, c) {
    if (a < b) {
        return a;
    }
    return c;
}

Case 2:

function (a, b, c) {
    var result;
    if (a < b) {
        result = a;
    } else {
        result = c;
    }
    return result;
}

This is a code style issue. There is no objective right answer although I'm sure everyone has their preference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top