首页 > 解决方案 > 使用 PHP 重新加载包含新 div 内容的页面

问题描述

我有一个包含主要内容和菜单栏的页面,当用户登录时,通过从数据库中提取的数据设置 $_SESSION 变量以确定用户看到的主要内容和菜单栏。

主页大致如下:

 <div id="menu">
    <?php include_once '/files/'.$_SESSION['menu']; ?>
    </div>

    <div>
    <?php include_once '/files/'.$_SESSION['content']; ?>
    </div>

当用户登录 $_SESSION 变量设置为“menu1.php”和“content1.php”或“menu2.php”和“content2.php”时,这工作正常并且页面加载正确。

然后,我在两个菜单栏上都包含了两个按钮:

  <form action='' method='POST'>
      <button type="submit" name="set1">Set 1</button>
    </form>
    <form action='' method='POST'>
      <button type="submit" name="set2">Set 2</i></button>
    </form>

还有两个“功能”:

 <?php
      if(isset($_POST['set2'])){
            unset($_SESSION['menu']);
            unset($_SESSION['content']);
            $_SESSION['menu'] = 'menu2.php';
            $_SESSION['content'] = 'content2.php';
      };
      if(isset($_POST['set1'])){
            unset($_SESSION['menu']);
            unset($_SESSION['content']);
            $_SESSION['menu'] = 'menu1.php';
            $_SESSION['content'] = 'conent1.php';
      };
     ?>

如果您要单击按钮将内容和菜单从 1 更改为 2,则页面会重新加载并显示正确的内容“content2”,但是,如果您只刷新页面,菜单栏将保持在“menu1”然后菜单是否更改为“menu2”,就好像菜单会话是一次刷新。反之亦然,从 2 到 1。

怎样做才能在页面重新加载时重新加载新内容和新菜单?

标签: phphtml

解决方案


首先,你不应该使用类似的东西:

<?php include_once '/files/'.$_SESSION['menu']; ?>

这是一个巨大的漏洞,阅读更多 - OWASP XSS。如果您由于某种原因不能使用任何其他解决方案,请使用:

<?php 
if ($_SESSION['menu'] == 'menu2.php') include_once '/files/menu2.php'; 
?>

对于您的问题 - 尝试使用以下代码:

<?php
  if(isset($_POST['set2'])){
        $_SESSION['menu'] = 'menu2.php';
        $_SESSION['content'] = 'content2.php';
        session_write_close();
  };
  if(isset($_POST['set1'])){
        $_SESSION['menu'] = 'menu1.php';
        $_SESSION['content'] = 'conent1.php';
        session_write_close();
  };
 ?>

您还可以延迟 1 秒对其进行测试:

header('Refresh: 1; URL=/');

推荐阅读