简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM