[英]redirect to login index page if user not logged in?
我的网站上有多个页面,其中大部分是会员页面,用户只能在登录后访问这些页面。
当用户登陆我的页面时,他们会自动登陆索引/主页 (index.php)。 如果用户试图导航到仅供会员使用的dashboard.php,那么他们应该被重定向回 index.php 以便他们可以登录。
在我所有成员页面的顶部,如dashboard.php 和 manage_account.php,我包含了一个 header.php 文件,如下所示:
include 'header.php';
用户登录后,我创建会话 '$_session['user']'
我正在使用以下标头重定向来检查会话是否存在,如果不存在,则重定向该用户。
<?php
session_start();
include 'config.php';
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
?>
我的问题不是将标题重定向代码剪切并粘贴到每个成员页面,我只想将它放在 header.php 页面中,因为这包含在我的所有成员页面中,包括我的主页 index.php。
但是它创建了一个连续的重定向并且不加载页面,它说网络
可能是因为标题也包含在索引中,对吗? 您可以在重定向之前检查条件:
<?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;
}
?>
您可以在 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;
}
希望能帮助到你!
在会员页面内做:
$memberOnly = true;
include 'header.php';
在 header.php 中:
if (isset($memberOnly)) {
if (empty($_SESSION['user'])) {
header('Location: index.php');
exit;
}
}
在公共页面(非会员可用)中,您只需:
include 'header.php'
不用担心$memberOnly
如果我正确理解您的问题,您的header.php
文件将包含在每个页面中。 虽然这个 header.php 文件包含执行的代码:
头文件.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 文件中。
如果您将代码提取到一个函数中并仅在需要登录用户的页面中调用它,您将避免此循环。
头文件.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;
}
}
?>
索引.php:
<?php
session_start();
include 'header.php';
// Public accessible pages do not call the function
...
?>
秘密.php:
<?php
session_start();
include 'header.php';
// Protected pages do call the function
redirectToLoginIfNecessary();
...
?>
这对我有用。 使用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 . '">';
}
在重定向之前添加此检查
if ($_SERVER["PHP_SELF" ] != "index.php")
您将 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;
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.