Я написал несколько строк кода, чтобы помочь вам начать с реализации вашей идеи.
Создать файл index.php
Первое, что нам нужно, - это обработать все запросы водно место, которое в нашем случае идет к файлу index.php
, расположенному в вашей основной папке приложения .
Настройка файла .htaccess
Мы [все еще]будем использовать .htaccess
rewriterule
, поэтому давайте начнем с добавления простого RewriteRule
в файл .htaccess
, который поможет нам скрыть index.php
от URI и перенаправить все запросы через файл index.php
:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^ index.php [L]
</IfModule>
Построение логики внутри файла index.php
Теперь мы готовы приступить к построению логики внутри файла index.php
.
Идея, о которой я подумалof создает каталог app
, который содержит все папки вашего приложения, что приводит к следующей структуре:
app
app\faq
app\faq\faq.php
.htaccess
index.php
Для этого я сделал следующее (объяснено ниже) код и вставьте его в 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);
На самом деле этот код берет имя файла из запроса uri и ищет его во всех подкаталогах $appDirectory
(рекурсивно), если файл найден, он будет include
d в файле index.php
, в противном случае будет отображаться ошибка.
ПРИМЕЧАНИЕ: Этот сценарий только для демонстрации, и онвсе еще нуждается в развитии. например В некоторых случаях у вас может быть два файла с одинаковыми именами в двух разных каталогах, этот скрипт будет отображать только первый найденный файл.
Я также предлагаю прочитать "Какпостроить базовую серверную систему маршрутизации на PHP ".