What are some best practices for using PHP to include navigation links on multiple pages while highlighting the current page with CSS?
When including navigation links on multiple pages using PHP, it's important to dynamically highlight the current page link using CSS to provide visual feedback to the user. One way to achieve this is by adding a CSS class to the current page link and styling it differently. This can be done by checking the current page URL against the link URLs in the navigation and adding the CSS class accordingly.
```php
<?php
$current_page = basename($_SERVER['PHP_SELF']);
$nav_links = array(
'Home' => 'index.php',
'About' => 'about.php',
'Services' => 'services.php',
'Contact' => 'contact.php'
);
echo '<ul>';
foreach ($nav_links as $title => $url) {
$class = ($current_page == $url) ? 'current' : '';
echo '<li><a href="' . $url . '" class="' . $class . '">' . $title . '</a></li>';
}
echo '</ul>';
?>
```
In the above code snippet, we first get the current page URL using `basename($_SERVER['PHP_SELF'])`. We then define an array of navigation links with their respective URLs. Inside the loop, we check if the current page URL matches the link URL, and if so, we add the CSS class 'current' to highlight it. Finally, we output the navigation links with the appropriate CSS class.
Keywords
Related Questions
- How can creating a separate table for rental transactions improve data management and tracking in a PHP and MySQL setup?
- Are there any specific pitfalls to avoid when trying to extract the current URL in PHP?
- How can PHP developers enhance the security of their contact forms to prevent spam submissions?