How can PHP developers ensure that links within a dynamically generated menu accurately reflect the file structure?
When dynamically generating a menu in PHP, developers can ensure that links accurately reflect the file structure by using the `$_SERVER['REQUEST_URI']` variable to dynamically set the active class on the current page link. This allows for the active link to be highlighted based on the current URL, providing a visual indication to users of their current location within the site.
<?php
$current_page = basename($_SERVER['REQUEST_URI']);
$menu_items = array(
'Home' => 'index.php',
'About' => 'about.php',
'Services' => 'services.php',
'Contact' => 'contact.php'
);
foreach ($menu_items as $title => $url) {
$class = ($current_page == $url) ? 'active' : '';
echo '<li><a href="' . $url . '" class="' . $class . '">' . $title . '</a></li>';
}
?>
Related Questions
- How can PHP developers prevent unauthorized users from requesting a new password for another user's account?
- How can data be stored in a database and retrieved using an ID when passing variables in PHP?
- What is the potential issue with including a PHP file in an HTML file and accessing a class defined in the included file?