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();
}
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();
}
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.