PHP: 重定向到子级应用页面时保留以前包含的文件(index.php)

PHP: Keep former included files when redirecting to sub level application page (index.php)

我以一种模块化的方式重构了我的网站。

对于我自己编写的网络应用程序,我有一个子文件夹结构。

现在我在顶层的中央入口点有管理不同 URL 的路由。

重定向到子级别 index.php 页面效果很好。

因为我在子目录中的 Web 应用程序有自己的 index.php 页面,当从顶级 index.php 页面重定向到它们时,我在顶级网站上的包含文件不见了。

当然,如果我只包含来自子级别应用程序的个人 pages/views,那么顶层包含仍然存在。但是子级别 index.php 文件中的所有逻辑都没有被使用,子级别应用程序不能再被认为是独立的。

所以我的问题是: 重定向 (header("location: ...")) 到子级应用程序 index.php 时,是否可以将包含内容保留在我的顶级 index.php 页面上?

这是我的文件夹结构: Folder structure

这是我的顶层代码index.php:

<?php

const DS = DIRECTORY_SEPARATOR;
define("PATH", $_SERVER["DOCUMENT_ROOT"] . DS);
require_once PATH . "config.php";

include_once "Route.php";

include_once PATH_VIEWS . "header.php";
include_once PATH_VIEWS . "banner.php";

if($_SESSION["loggedIn"]) include_once PATH_VIEWS . "menu.php";

// Routes

Route::add("/", function(){
  // Check Session
  if(!$_SESSION["loggedIn"]){
    // Goal: Redirect to module / sub site "sso" while keeping 
    // the included header.php and banner.php
    header("location:/login");
    exit();
  }
  include PATH_VIEWS . "welcome.php";
});

Route::add("/login", function(){
  header("location: /apps/sso/");
  exit();
});

Route::run();

您应该创建一个控制器页面来管理所有 url 请求, 为此,您需要创建一个 htaccess 规则来将所有请求导航到该文件

正如 CD001 所提到的:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

例如,如果请求的文件不存在,此代码会将所有请求导航到根 index.php。

这允许您控制在 url 请求时发生的情况。 在此文件中,您可以选择要导入的内容以及导入的时间 url

例如:

index.php:
<?php
    //here you can include whatever you want to be included in any url
    if ($_SERVER['REQUEST_URI'] == '/login') {
        require_once 'login.php'; // as an example
    } /*else if (url == any other url) {
        require again what you want to be required in this url
    }*/
?>

通过这种方式,您可以控制在您网站的任何页面中包含的内容,而无需在每个页面中再次要求。