如何将会话限制为仅在PHP中的目录? [英] How to restrict a session to a directory only in PHP?
问题描述
我的网站上有一个管理系统和一个用户系统.用户系统上的某些数据不会更改,但管理员数据会更改.所以我想知道是否有一种方法可以将管理员会话(当他们登录时)仅限制在管理员目录(/admin)中,以免干扰我网站的其余部分?
I have an admin system and a user system on my website. Some data on the user system will not change, but the admin data will change instead. So I was wondering if there was a way to restrict the admin session (when they login) only to the admin directory (/admin), so that it does not interfere with the rest of my website?
谢谢
卢卡斯
推荐答案
有很多处理此类问题的方法.可能最简单的方法是检查权限和$_SERVER['REQUEST_URI']
,如果用户不在admin/
区域中,则重定向到该区域.
There are many ways to handle something like this. Probably the easiest is to check the permissions and $_SERVER['REQUEST_URI']
, and if the user isn't in the admin/
area, redirect into it.
// Assuming you've saved an admin flag in session
// and the user request URI doesn't contain admin/
if ($_SESSION['admin'] === TRUE && !preg_match('/admin\//' $_SERVER['REQUEST_URI'])) {
// redirect into the admin/ area
header("Location: http://example.com/admin");
exit();
}
更新:
根据普遍要求,以下是在admin/目录中强制执行管理员登录的相反操作
Update:
By popular request, here's the reverse to enforce an admin login in the admin/ directory
if ((!isset($_SESSION['admin'] || $_SESSION['admin'] === FALSE) && preg_match('/admin\//' $_SERVER['REQUEST_URI'])) {
// redirect out of the admin/ area
header("Location: http://example.com/");
exit();
}
实际上,假设管理页面是单独的脚本,那么您实际上不需要这部分中的preg_match()
.但是,如果您使用的MVC模式可能实际上无法从admin目录中的文件提供管理脚本,请使用regex匹配项.
Actually, assuming the admin pages are separate scripts, you don't really need the preg_match()
in this part. But if you have an MVC pattern where the admin script may not actually be served from a file in the admin directory, use the regex match.
这篇关于如何将会话限制为仅在PHP中的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!