验证管理员是否已登录 php

Validate admin is logged in php

我有一个生成 RSS 提要的 php 脚本,但我只希望管理员可以访问它。我目前使用这个方法

if($_SESSION['isAdmin'] != true) {
  $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
  header("Location: /");
}

它在其他页面上有效,但出于某种原因在此处无效。

我想要它的页面,验证用户是管理员($_SESSION['isAdmin] == true),执行更新 RSS 文件的脚本,重定向回常规 admin 页面。

这是页面的基本框架。我删除了所有无关紧要的东西

<?php

  if($_SESSION['isAdmin'] != true) {
    $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
    header("Location: /");
  }

  $file = fopen('rss.xml', "w") or die("Unable to open file");

  try {
    // Connect to db
    $conn = new PDO("mysql:host=" . SERVERNAME . ";" . "dbname=" . DBNAME, USERNAME, PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = $conn->query('SELECT * FROM * ORDER BY upload_date DESC ');
    $result = $query->fetchAll(PDO::FETCH_OBJ);

    $rssfeed = 'This gets set based on what the db returns';

  } catch (PDOException $e) {
    echo $e->getMessage();
  }

  fwrite($file, $rssfeed);
  fclose($file);

  header("Location: /admin.php");

在我的测试中,当我没有登录时,它仍然执行脚本(生成 rss.xml 文件),然后将我重定向回管理页面。我没有登录,因此将我重定向回 /,错误提示我不允许访问 admin.php

发送 Location header 后,您需要 exit

header函数只是在最终发送的结果上加了一个header。因为你没有 exit,后面的所有代码仍然执行,并且该代码的输出连同 Location header.

exit() 添加到位置 header 重定向的末尾。这将阻止之后的代码被执行。

<?php

  if($_SESSION['isAdmin'] != true) {
    $_SESSION['sessionErrors'][] = "Sorry, you are not allowed access the page 'Update RSS Feed'";
    header("Location: /");
    exit(); // It will stop here.
  }

// The rest of the code
.........

阅读评论后我意识到我从来没有用 session_start();

开始会话

不过,我还在重定向的末尾添加了 exit();,因为我想这似乎是个好习惯。

仍在学习很多关于 php 的知识,所以非常感谢你们给我的任何建议。感谢您的帮助!!