简体   繁体   English

如果用户未登录,则限制 PHP 文件?

[英]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.我在我想要限制访问的文件顶部有这个 if 语句。

<?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.如果我没有登录,我会收到 echo “请先登录以查看此页面。但是受限中的 HTML 仍在显示。用户名和密码存储在 MySQL 数据库中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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