Index.php can’t find the route/path of the desired files [closed]

Explanation:

I’m making a website (new to this) and wanted to make a system to handle all requests to make maintainece easier.

Idea

When a file needs to go to another path, it would go through index.php and index will reveal the path and direct it there. (A router)
And when the webserver files need to access the database(which is private) they will ask index.php to ask hub.php and hub.php will give the desired information from database.

Issues

Index.php isn’t able to find the path or connect them even though i gave the correct code.

My Files:

Folder/
    ├── database/
    │   ├── accounts/
    │   │   ├── orders/
    │   │   ├── reviews/
    │   │   └── users.json
    │   ├── designs/
    │   └── system/
    │       └── logo.png
    ├── root/
    │   ├── 0/
    │   │   ├── admin.php
    │   ├── 1/
    │   │   └── main.php
    │   ├── 2/
    │   │   ├── catalog.php
    │   │   ├── checkout_system/
    │   │   ├── design.php
    │   │   ├── functions.php
    │   │   └── list-catalog/
    │   ├── 3/
    │   │   └── contact.php
    │   ├── 4/
    │   │   ├── reviews.php
    │   │   └── submit_review.php
    │   ├── 5/
    │   │   ├── bulk-purchase/
    │   │   └── list.php
    │   ├── 6/
    │   │   └── login.php
    │   ├── 7/
    │   │   ├── footer.php
    │   │   └── header.php
    │   └── index.php
    └── hub.php

My index.php code:

<?php
error_reporting(0);
ini_set('display_errors', 0);
define('LOG_FILE', __DIR__.'/security.log');
register_shutdown_function(function() {
    if ($error = error_get_last()) {
        error_log(date('[Y-m-d H:i:s] ').print_r($error,1)."n", 3, LOG_FILE);
    }
});

session_start([
    'cookie_httponly' => 1,
    'cookie_samesite' => 'Strict',
    'sid_length' => 128,
    'sid_bits_per_character' => 6
]);

// Route mapping
$routes = [
    '/' => '/1/main.php',
    '/main' => '/1/main.php',
    '/catalog' => '/2/catalog.php',
    '/design' => '/2/design.php',
    '/contact' => '/3/contact.php',
    '/reviews' => '/4/reviews.php',
    '/submit-review' => '/4/submit_review.php',
    '/login' => '/6/login.php',
    '/logout' => '/6/logout.php',
    '/admin' => '/0/admin.php'
];

// Get requested path
$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);

// Find matching route
foreach ($routes as $route => $file) {
    if ($requestPath === $route) {
        $absolutePath = __DIR__.$file;
        
        // 100% file existence guarantee
        if (!file_exists($absolutePath)) {
            error_log("Missing route file: $absolutePath", 3, LOG_FILE);
            http_response_code(500);
            exit('System configuration error. Admin notified.');
        }
        
        // Generate CSRF token (once per session)
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        
        // Authentication check
        $protectedRoutes = ['/admin', '/submit-review'];
        if (in_array($route, $protectedRoutes) && empty($_SESSION['user'])) {
            header('Location: /login');
            exit;
        }
        
        include $absolutePath;
        exit;
    }
}

// 404 Handling
http_response_code(404);
$contactPath = __DIR__.'/root/3/contact.php';
if (file_exists($contactPath)) {
    include $contactPath;
} else {
    echo '<h1>404 - Page Not Found</h1>';
}

My hub.php code:

<?php
// Armored session
session_start([
    'cookie_httponly' => 1,
    'cookie_samesite' => 'Strict'
]);

// JSON responses
header('Content-Type: application/json');

// Request validation fortress
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['error' => 'POST requests only']));
}

$refererHost = parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_HOST);
$serverHost = $_SERVER['HTTP_HOST'] ?? '';
if ($refererHost !== $serverHost) {
    http_response_code(403);
    exit(json_encode(['error' => 'Cross-origin requests forbidden']));
}

// CSRF vault
$token = $_POST['csrf_token'] ?? '';
if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
    http_response_code(403);
    exit(json_encode(['error' => 'Security token mismatch']));
}

function verifyAuth() {
    if (empty($_SESSION['user'])) {
        http_response_code(401);
        exit(json_encode(['error' => 'Authentication required']));
    }
}

try {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'login':
            $username = $_POST['username'] ?? '';
            $password = $_POST['password'] ?? '';
            
            // Load users
            $users = json_decode(file_get_contents(__DIR__.'/database/accounts/users.json'), true) ?: [];
            foreach ($users as $id => $user) {
                if ($user['username'] === $username && password_verify($password, $user['password'])) {
                    $_SESSION['user'] = [
                        'id' => $id,
                        'name' => $user['name'],
                        'level' => $user['level'] ?? 1
                    ];
                    session_regenerate_id(true);
                    exit(json_encode(['success' => true]));
                }
            }
            exit(json_encode(['success' => false, 'error' => 'Invalid credentials']));
            
        case 'get_designs':
            $designs = [];
            $path = __DIR__.'/database/designs/';
            
            // Glob with absolute security
            foreach (glob($path.'*.{jpg,png,webp}', GLOB_BRACE) as $file) {
                $designs[] = [
                    'name' => basename($file),
                    'url' => '/database/designs/'.rawurlencode(basename($file))
                ];
            }
            exit(json_encode(['designs' => $designs]));
            
        case 'submit_review':
            verifyAuth();
            $data = [
                'id' => 'rev_'.bin2hex(random_bytes(8)),
                'user_id' => $_SESSION['user']['id'],
                'name' => $_POST['name'] ?? '',
                'rating' => max(1, min(5, (int)($_POST['rating'] ?? 5))),
                'comment' => substr($_POST['comment'] ?? '', 0, 500),
                'date' => date('Y-m-d H:i:s')
            ];
            
            // Write with atomic safety
            $tmpFile = tempnam(sys_get_temp_dir(), 'rev');
            file_put_contents($tmpFile, json_encode($data));
            rename($tmpFile, __DIR__."/database/accounts/reviews/pending/{$data['id']}.json");
            
            exit(json_encode(['success' => true]));
            
        default:
            http_response_code(400);
            exit(json_encode(['error' => 'Invalid action']));
    }
} catch (Throwable $e) {
    http_response_code(500);
    exit(json_encode(['error' => 'System processing error']));
}

Attempted Troubleshooting:

  • I made sure they are the exact path
  • i asked ai if there is error in the code and it said no