What are some common methods for handling URL routing and page inclusion in PHP?
When developing a PHP website, handling URL routing and page inclusion is essential for directing users to the correct pages based on the URL they are accessing. One common method is to use a switch statement to map URLs to specific PHP files or functions that will handle the request. Another approach is to use a front controller pattern, where all requests are directed to a single PHP file that then includes the appropriate page based on the URL parameters.
// Example of URL routing using a switch statement
$url = $_SERVER['REQUEST_URI'];
switch ($url) {
case '/':
include 'home.php';
break;
case '/about':
include 'about.php';
break;
case '/contact':
include 'contact.php';
break;
default:
include '404.php';
break;
}
```
```php
// Example of URL routing using a front controller pattern
$url = $_SERVER['REQUEST_URI'];
$routes = [
'/' => 'home.php',
'/about' => 'about.php',
'/contact' => 'contact.php'
];
if (array_key_exists($url, $routes)) {
include $routes[$url];
} else {
include '404.php';
}