Just Lucky Really
Just Lucky Really

Reputation: 1401

PHP best practice when redirecting unauthenticated users

Okay, so I've seen a couple of different approaches for redirecting a user when, for example, they are not logged in, or are not allowed to view a page, and decide to redirect.

I'll set the scene ... Let's say, when a user has provided a correct username and password, the session variable $_SESSION['loggedin'] is created. Now, when this user goes to logged_in_users_only.php, he can happily see the page. But, along comes Danger Jim, who hasn't logged in, and goes to logged_in_users_only.php and get's redirected back to the home page (Maybe with a warning)

So. here's the 2 main approaches I have seen, and was wondering if either of them have security implications, or could somehow allow Danger Jim to see the logged_in_users_only.php page

Example 1

if(session_status()==PHP_SESSION_NONE) {
    session_start();
}
if(isset($_SESSION['loggedin'])) {
    //show content
} else {
    header('Location: home.php');
    exit;
}

Example 2

if(session_status()==PHP_SESSION_NONE) {
    session_start();
}
if(!isset($_SESSION['loggedin'])) {
    header('Location: home.php');
    exit;
}
//show content

Personally, I have always gone with the first approach. I think it's because the code seems to sit nicely 'trapped' within the brackets (Maybe I just like looking at it that way Lol).

But I am intrigued to know if example 2 could never let Danger Jim see the content.

Upvotes: 2

Views: 285

Answers (1)

Goudgeld1
Goudgeld1

Reputation: 362

I think this is quite a good question so I will try to give a good answer!

Both examples will work and the biggest difference is that it indeed looks safer in the first example. But both do the same thing. There is just one thing you have to consider, in the first example:

if(session_status()==PHP_SESSION_NONE) {
    session_start();
}
if(isset($_SESSION['loggedin'])) {
    echo "logged in!";
} else {
    header('Location: home.php');
    Exit;
}

You have to echo all your content. some IDE's don't support HTML coloring inside of the PHP echo function.

I personaly use the second example becous my IDE doesn't support code coloring inside PHP strings.

if(session_status()==PHP_SESSION_NONE) {
    session_start();
}
if(!isset($_SESSION['loggedin'])) {
    header('Location: home.php');
    Exit;
}

After the header();, the page is closed so there is no 'real' danger by using the second example. If you want some more details, you should read the header manual if you haven't already.

Good Luck with your code and I hope we at stackoverflow helped you to become a better programmer. They helped me a lot :)

p.s. Sorry for my bad english

Upvotes: 1

Related Questions