Search code examples
phpapacheurl-routing

PHP routing not including files



I tried a simple routing for PHP but I'm getting crazy because it's not fully working...
Hope anyone can help. This is my first try to write an own routing with PHP.

Problem

When I request "SERVER-IP/hms/routing/test" it shows content of home.php - ok

When I request "SERVER-IP/hms/routing/shop" it shows 404-error.... - why??
As soon as I'm deleting "shop.php" on server, it shows my index.php with

Request:/hms/routing/shop
URL: /shop

Don't know why it's not loading the files properly...
Any idea why it's not working? :(

My .htaccess

RewriteEngine On
RewriteBase /hms/routing
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [L,QSA]

My index.php

<?php

$request = $_SERVER['REQUEST_URI'];

echo "Request:".$request."<br>";

$url = str_replace("/hms/routing","", $request);

echo "URL: ".$url."<br>";

switch ($url) {
    case "/":
        include "home.php";
        break;
        
    case "/about":
        include "about.php";
        break;
        
    case "/test":
        include "home.php";
        break;
        
    case "/shop":
        include "shop.php";
        break;
        
}
?>

Thanks a lot in advance! :)


Solution

  • Finally it worked!
    Thanks to Will B., the solution is as follows:

    .htaccess

    Options -MultiViews
    RewriteEngine On
    RewriteBase /hms/routing
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ index.php?url=$1 [L,QSA]
    

    index.php

    <?php
    
    $request = $_SERVER['REQUEST_URI'];
    
    echo "Request:".$request."<br>";
    
    $url = str_replace("/hms/routing","", $request);
    $url = trim($url);
    
    echo "URL: ".$url."<br>";
    echo "Complete: ". __DIR__ . $url.".php<br>";
    
    
    switch ($url) {
        case "/":
            require_once __DIR__ . '/home.php';
            break;
            
        case "/about":
            require_once __DIR__ . '/about.php';
            break;
            
        case "/test":
            require_once  __DIR__ . '/home.php';
            break;
            
        case "/shop":
            require_once __DIR__ . '/shop.php';
            break;
            
    }
    

    I think what finally helped was Options -MultiViews in .htaccess

    Thanks a lot for help! :)