I wrote some lines of code to help you out starting with the realization of your idea.
Create the index.php
file
The first thing we need is to process all requests in one place, which is in our case going to the index.php
file located in your main application folder.
Configuring the .htaccess file
We are [still] going to use the .htaccess
rewriterule
, so let's start by adding a basic RewriteRule
to the .htaccess
file that will help us hide the index.php
from the URI and redirect all requests through the index.php
file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^ index.php [L]
</IfModule>
Building the logic inside the index.php
file
Now we are ready to start building the logic inside the index.php
file.
The idea i thought of is making an app
directory that contains all of your application's folders, which results in the following structure:
app
app\faq
app\faq\faq.php
.htaccess
index.php
To achieve this, i have made the following (explained below) code and inserted it into the index.php
:
<?php
//This function is from: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/
function getSubDirectories($dir)
{
$subDir = array();
$directories = array_filter(glob($dir), 'is_dir');
$subDir = array_merge($subDir, $directories);
foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
return $subDir;
}
function response(string $appDir, string $uri)
{
$currentDir = __DIR__;
$currentDirBaseName = basename($currentDir); //Get the the basename of the current directory
$filename = str_replace('/'.$currentDirBaseName.'/', '', $uri); //Remove the current directory basename from the request uri
if(strpos($filename, '/') > -1) { //If the user is asking for a directory respond with an exception
http_response_code(404);
echo "The requested file was not found.";
}
foreach(getSubDirectories($currentDir.'/'.$appDir) as $dir) { //Iterate through all the subdirerctories of the app directory
$file = $dir.'/'.$filename; //Filename
if(!is_dir($file) && file_exists($file)) { //If the $file exists and is not a directory, `include()` it
include($dir.'/'.$filename);
exit; //or return;
}
}
http_response_code(404);
echo "The requested file was not found.";
}
//Get the request uri
$uri = $_SERVER['REQUEST_URI'];
//Define the app directory
$appDirectory = 'app';
response($appDirectory, $uri);
What this code actually does is taking the filename from the request uri
and looking for it in all of the $appDirectory
subdirectories (recursively), if
the file is found it will be include
d in the index.php
file , else an error will be displayed.
NOTE: This script is just for demonstration, and it still needs development. e.g. In some cases you might have two files with the same names in two different directories, this script will only display the first file it finds.
I also suggest reading "How to build a basic server side routing system in PHP".