It looks like you're trying to implement a simple routing mechanism in PHP, but there are a few issues in your code that might be causing the problem. Let's go through them step by step.
-
Ensure the URLs are correctly matched: The
urlIsfunction should be checking the path part of the URL, not the entire URL. Also, make sure the paths in your$routesarray match exactly what you expect in the$_SERVER['REQUEST_URI']. -
Check for trailing slashes: Sometimes, URLs with and without trailing slashes are treated differently. Ensure consistency in your routing logic.
-
Debugging: Add some debugging statements to see what the actual values are.
Here's a revised version of your code:
nav.php
<div class="ml-10 flex items-baseline space-x-4">
<a href="/" class="<?= urlIs('/') ? 'bg-gray-900 text-white' : 'text-gray-300' ?> px-3 py-2 text-sm font-medium text-white">Home</a>
<a href="/about" class="<?= urlIs('/about') ? 'bg-gray-900 text-gray-300' : 'text-gray-300' ?> px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white">About</a>
<a href="/contact" class="<?= urlIs('/contact') ? 'bg-gray-900 text-gray-300' : 'text-gray-300' ?> px-3 py-2 text-sm font-medium text-gray-300 hover:bg-gray-700 hover:text-white">Contact</a>
</div>
index.php
<?php
require 'functions.php';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$routes = [
'/' => 'controllers/index.php',
'/about' => 'controllers/about.php',
'/contact' => 'controllers/contact.php',
];
if (array_key_exists($uri, $routes)) {
require $routes[$uri];
} else {
echo "Route not found for URL: " . htmlspecialchars($uri);
}
?>
functions.php
<?php
function urlIs($value)
{
return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) === $value;
}
?>
Explanation:
-
nav.php: TheurlIsfunction is used to determine the active link. The class names are applied based on the current URL. -
index.php: Theparse_urlfunction is used to get the path part of the URL. This ensures that query parameters do not interfere with routing. -
functions.php: TheurlIsfunction is updated to useparse_urlto compare only the path part of the URL.
This should resolve the issue with your routing. If you still encounter problems, make sure to check the actual values of $_SERVER['REQUEST_URI'] and $uri by adding some var_dump or echo statements for debugging.