[英]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");
如果未登錄,則會顯示一個登錄表單。 我這里有兩個問題:
有什么方法可以將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.