簡體   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