如果用户未登录,重定向到登录索引页面?

redirect to login index page if user not logged in?

我的网站上有多个页面,其中大部分是会员专享页面,用户只有在登录后才能访问这些页面。

当用户登陆我的页面时,他们会自动登陆 index/home 页面 (index.php)。如果用户试图导航到仅供会员使用的 dashboard.php,则应将他们重定向回 index.php,以便他们可以登录。

在我所有会员页面的顶部,如 dashboard.php 和 manage_account.php 我包含一个 header.php 文件,如下所示:

include 'header.php';

用户登录后,我创建 session '$_session['user']'

我正在使用以下 header 重定向来检查 session 是否存在,如果不存在则重定向该用户。

<?php
session_start(); 
include 'config.php';

if (empty($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

?>

我的问题不是将 header 重定向代码剪切并粘贴到每个会员页面,而是我只想将它放在 header.php 页面中,因为它已包含在我所有的页面中会员页面包括我的主页 index.php.

但是它创建了一个连续的重定向并且不加载页面,它说网络

在会员页面中执行:

$memberOnly = true;
include 'header.php';

并在 header.php 中:

if (isset($memberOnly)) {
    if (empty($_SESSION['user'])) {
      header('Location: index.php');
      exit;
    }
}

在 public 页中(非会员可用)您只需:

include 'header.php'

不用担心$memberOnly

可能是因为 header 也包含在索引中,对吧?您可以在重定向之前检查条件:

<?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;

}

希望对您有所帮助!

在重定向之前添加此检查

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;
}
?>

如果我正确理解你的问题,你的 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();
...
?>

这对我有用。 使用 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 . '">';
}