[英]Restrict PHP file if user is not logged in?
我试图阻止未登录的用户访问我的网页访问某个文件。 我在我想要限制访问的文件顶部有这个 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');
}
?>
问题是,如果我登录,我确实会收到“欢迎来到会员区”。 如果我没有登录,我会收到 echo “请先登录以查看此页面。但是受限中的 HTML 仍在显示。用户名和密码存储在 MySQL 数据库中。
颠倒执行此操作的顺序可能会更好,因此您不必将所有代码包含在一个块中,并且如果用户未登录,您可以终止您的页面。
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.