Niqqo
Niqqo

Reputation: 41

Restrict PHP file if user is not logged in?

I'm trying to prevent not signed in users to my webpage access to a certain file. I have this if statement at the top of the file I want to have restricted access.

<?php
    session_start();
    if (isset($_SESSION['user']) && $_SESSION['user'] == true) {
        echo "Welcome to the member's area, " . $_SESSION['user'] . "!";
    } else {
         echo "Please log in first to see this page.";
         header ('index.php');
    }
 ?>

The thing is that if I'm signed in I do get the "Welcome to members area". And if I'm not signed in I get echo "Please log in first to see this page. However the HTML in the restricted is still showing. The user name and password are stored in a MySQL database.

Upvotes: 0

Views: 1280

Answers (1)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

It's probably better to reverse the order that you do this, so you don't have to contain all of your code in a block, and you can kill your page if the user is not logged in.

session_start();

//empty does both of the checks you are doing at once
//check if user is logged in first
if(empty($_SESSION['user'])) {

    //give error and start redirection to login page
    //you may never see this `echo` because the redirect may happen too fast
    echo "Please log in first to see this page.";
    header('Location: index.php');

    //kill page because user is not logged in and is waiting for redirection
    die();
}

echo "Welcome to the member's area, " . $_SESSION['user'] . "!";

//more page code here

Upvotes: 1

Related Questions