How can the basename() function in PHP be used to dynamically generate titles for different PHP files when including a shared header file?
When including a shared header file in different PHP files, you can use the basename() function in PHP to dynamically generate titles for each page based on the filename of the included file. This allows you to have unique page titles without hardcoding them in each individual file.
<?php
$currentPage = basename($_SERVER['PHP_SELF']);
switch($currentPage) {
case 'index.php':
$pageTitle = 'Home Page';
break;
case 'about.php':
$pageTitle = 'About Us';
break;
case 'contact.php':
$pageTitle = 'Contact Us';
break;
default:
$pageTitle = 'My Website';
}
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageTitle; ?></title>
</head>
<body>
<?php include 'header.php'; ?>
<!-- Rest of your page content -->
</body>
</html>
Related Questions
- What are some best practices for retrieving and displaying specific user videos using the YouTube API in PHP?
- What are the best practices for handling and merging two tables in PHP before inserting them into a SQL database?
- How can PHP be used to dynamically determine and display the current page a user is on within a paginated forum?