重定向PHP中的include而不重定向主页


Redirect an include in PHP without redirecting main page

我有一个带有index.php的网站,它看起来像这样:

<?php
ob_start();
include_once 'config.php';
include_once 'dbconn.php';

session_start();

?>
<html>
<body>
<p>Some content</p>
<br>
<?php include_once 'loginform.php'; ob_end_flush(); ?>
</form>
</body>
</html>

loginform.php检查用户cookie以查看他们是否登录,如果是,则重定向到account.php:

$regAddr = mysqli_query($conn, "SELECT * FROM users WHERE address = '$addr'");
$addrRow = mysqli_num_rows($regAddr);
//check if address is in db
if($addrRow !== 0) {
    header("Location: account.php");

如果他们没有登录,它会显示一个登录表单。我有两个问题:

  1. 如果我删除ob_start()和ob_end_flush(),那么头将在include行上发送,并且我无法重定向
  2. 如果我离开它们并且用户登录,那么整个index.php将重定向到account.php

有没有办法将login.php重定向到account.php,同时保持index.php静态(不刷新)并且不使用iframes?

否。整个文档将被重定向,因为您知道loginform.php的行为与iframe类似,但它的行为与整个文档的一部分类似。

你有很多可用的选择来实现这一点。。。我不建议使用Iframe,而是使用一个类或函数来验证用户登录,然后根据结果包括一个文件。

<?php
if($logedin) {
     include("dashboard.php");
} else {
     include("loginform.php");
}

显然,这可以通过多种方式实现,我建议使用验证会话的类和渲染视图的类,这样你就不必为要加载的每个视图重复HTML头或类似的东西。

我的一个系统使用的真实代码。

<?php
include_once("../models/class-Admin.php");
class AdminViewRender {
    public static function render() {
        $request = "home";
        $baseFolder = "../views/admin/";
        //index.php?url=theURLGoesHere -> renders theURLGoesHere.php if
        //exists, else redirects to the default page: home.php
        if(isset($_GET["url"])) {
            if(file_exists($baseFolder.$_GET["url"].".php")) {
                $request = $_GET["url"];
            } else {
                header("Location: home");
            }
        }
        $inc = $baseFolder.$request.".php";
        if($request !== "login") { //if you are not explicitly requesting login.php 
            $admin = new Admin();
            if($admin->validateAdminSession()) { //I have a class that tells me if the user is loged in or not
                AdminPanelHTML::renderTopPanelFrame(); //renders <html>, <head>.. ETC
                include($inc); //Includes requestedpage
                AdminPanelHTML::renderBottomPanelFrame(); //Renders some javascript at the bottom and the </body></html>
            } else {
                include($baseFolder."login.php"); //if user validation (login) fails, it renders the login form.
            }
        } else {
            include($inc); //renders login form because you requested it
        }
    }
}