Under htdocs
folder i have created folder called PHP
under that i have created file called index.php
. I have written wrouting PHP code but it is not working.
index.php
<?php
echo "Welcome" . "<br>";
$routes = [];
route('/', function () {
echo "Home Page";
});
route('/login', function () {
echo "Login Page";
});
route('/about-us', function () {
echo "About Us";
});
route('/404', function () {
echo "Page not found";
});
function route(string $path, callable $callback) {
global $routes;
$routes[$path] = $callback;
}
run();
function run() {
global $routes;
$uri = $_SERVER['REQUEST_URI'];
$found = false;
foreach ($routes as $path => $callback) {
if ($path !== $uri) continue;
$found = true;
$callback();
}
if (!$found) {
$notFoundCallback = $routes['/404'];
$notFoundCallback();
}
}
http://localhost/PHP/
Welcome
Page not found
http://localhost/PHP/index.php/login/ (getting below output)
Welcome
Page not found
Expected output
Welcome
Login Page
Here wt am doing mistake, can anyone explain and update my code
My Answer:
The issue is with the way you are trying to match the routes. The `$_SERVER['REQUEST_URI']` variable includes the full path including the script name (index.php) and any query parameters.
To fix this, you can use `parse_url()` function to extract the path from the URL. Here's the updated code:
php
echo "Welcome" . "
";
$routes = [];
route('/', function () {
echo "Home Page";
});
route('/login', function () {
echo "Login Page";
});
route('/about-us', function () {
echo "About Us";
});
route('/404', function () {
echo "Page not found";
});
function route(string $path, callable $callback) {
global $routes;
$routes[$path] = $callback;
}
run();
function run() {
global $routes;
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$found = false;
foreach ($routes as $path => $callback) {
if ($path !== $uri) continue;
$found = true;
$callback();
}
if (!$found) {
$notFoundCallback = $routes['/404'];
$notFoundCallback();
}
}
With this change, the code should now correctly match the routes and display the expected output.
Rate this post
4 of 5 based on 5472 votesComments