繁体   English   中英

重定向PHP中的包含内容,而无需重定向主页

[英]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(),则会在包含行上发送标头,并且无法重定向。
  2. 如果我离开它们,并且用户已登录,则整个index.php都将重定向到account.php。

有什么方法可以将login.php重定向到account.php,同时保持index.php静态(不刷新)并且不使用iframe?

不会。整个文档将被重定向,因为您假设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
        }

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM