Skip to content
Advertisement

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

I restructed my website in a kind of modular way.

For my self written web apps I have a sub folder structure.

Now my central entry point on top level has routes to manage different URLs.

The redirect to the sub level index.php pages work great.

As my web apps in the sub directories have own index.php pages, when redirecting to them from the top level index.php page, my included files on top level site are gone.

Of course the includes on top level stay if i just include the individual pages/views from the sub level application. But then all the logic in the sub level index.php files is not used and the sub level apps cannot be considered standalone anymore.

So my question is: Is it possible to keep the includes on my top level index.php page when redirecting (header(“location: …”)) to a sub level application index.php?

Here is my folder structure: Folder structure

Here is my code of the top level 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();

Advertisement

Answer

You should create a controller page that manages all url requests, for that matter you need to create a htaccess rule to navigate all the request to this file

As CD001 mentioned here : https://stackoverflow.com/a/18406686/14648190

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

this code for example navigate all requests to the root index.php if the file requested is not exists.

this allows you to control what happened if a url requested. inside this file you can choose what to import and when for which url

for example:

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
    }*/
?>

this way you can control what to include in any page in your website instead of requiring again in each page.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement