我的网站上有多个页面,其中大多数是仅限会员的页面,用户只有登录后才能访问这些页面。
当用户登陆我的页面时,他们会自动登陆索引/主页(index.php)。如果用户尝试导航到仅用于成员的dashboard.php,则应将它们重定向回index.php,以便他们可以登录。
在我的所有成员页面的顶部,如dashboard.php和manage_account.php,我包括一个header.php文件,如下所示:
include 'header.php';
用户登录后,我会创建会话' $ _会话['用户']'
我正在使用以下标题重定向来检查会话是否存在以及它是否没有重定向该用户。
<?php
session_start();
include 'config.php';
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
?>
我的问题不是将标题重定向代码剪切并粘贴到每个成员页面,我只想将它放在header.php页面中,因为这包含在我的所有成员页面中,包括我的主页索引。 PHP。
然而,它创建了一个连续的重定向,并且没有加载页面,它说网络
答案 0 :(得分:3)
可能是因为标题也包含在索引中,对吧?您可以在重定向之前检查条件:
<?php
session_start();
include 'config.php';
if (empty($_SESSION['user']) && parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) != '/index.php') {
header('Location: index.php');
exit;
}
?>
答案 1 :(得分:2)
您可以在config.php中设置一个数组,其中需要验证哪些页面,然后与当前页面进行比较以定义是否验证。
例如:
$member_pages = array('dashboard', 'member-page', 'etc');
$current = $_SERVER['REQUEST_URI'];
if (empty($_SESSION['user']) && array_search($current, $member_pages) !== FALSE) {
header('Location: index.php');
exit;
}
希望它有所帮助!
答案 2 :(得分:0)
在会员页面内执行:
$memberOnly = true;
include 'header.php';
并在header.php中:
if (isset($memberOnly)) {
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
}
在公共页面(非会员可用)中,您只需:
include 'header.php'
不用担心$memberOnly
答案 3 :(得分:0)
如果我正确理解您的问题,您的header.php
文件将包含在每个页面中。虽然这个header.php文件包含执行的代码:
的header.php:
<?php
// This code is executed whenever you include this file
session_start();
include 'config.php';
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
?>
您获得了重定向循环,这意味着此代码也在index.php
页面中执行。也许header.php文件也包含在index.php文件中。
如果要将代码提取到函数并仅在需要登录用户的页面中调用它,则可以避免此循环。
的header.php:
<?php
// The code in this function is not called automatically when the file is included
function redirectToLoginIfNecessary()
{
if (!isset($_SESSION['user'])) {
header('Location: index.php');
exit;
}
}
?>
的index.php:
<?php
session_start();
include 'header.php';
// Public accessible pages do not call the function
...
?>
secret.php:
<?php
session_start();
include 'header.php';
// Protected pages do call the function
redirectToLoginIfNecessary();
...
?>
答案 4 :(得分:0)
这对我有用。 使用 header 是最好的,但必须在任何其他内容发送到浏览器之前使用。这对我来说,在 schmurdpress 中开发,很难实现。
if ( is_user_logged_in() ) {
echo 'Cool!';
} else {
$url = "https://yourdomain.com/log-in/";
echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $url . '">';
}
答案 5 :(得分:-1)
在重定向
之前添加此检查if ($_SERVER["PHP_SELF" ] != "index.php")
答案 6 :(得分:-1)
您将index.php重定向到index.php - 如果访问文件是index.php,则不应该触发重定向。
<?php
session_start();
include 'config.php';
$basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
if ((empty($_SESSION['user'])) && ($basename!="index")) {
header('Location: index.php');
exit;
}
?>