Show different header title depending on page
Show different header title depending on page
I’ve used this options for different situation and it does work properly. I can use this to specify not only the specific header title, but also to include different style CSS or javascripts based on the specific page or whatever you need included for that page only.
In case you use static pages, I recommend using something like this in your actual page, for example the contact.php file:
1 2 3 |
<?php $page = 'contact'; include_once('header.php'); |
And then using that page variable directly into the header.php file as bellow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
switch ($page) { case 'index': //code to be executed if $page=index; echo "<h1>This title is for index page</h1>"; break; case 'contact': //code to be executed if $page=contact; echo "<h1>This title is for contact page</h1>"; break; case 'some-other-page': //code to be executed if $page=some-other-page; echo "<h1>This title is for some other page</h1>"; break; default: //code to be executed if $page is different from all other cases; } |
This is pretty simple right? It will switch to the specific section of the code and execute it if the $page
value is one of the 3 pages, else will use the default
part.
Always use a default section just in case you did something wrong and hopefully don’t break the page experience for the user.
Now you can do something much simpler in just the header.php file, this would only work if you actually have a page
parameter in your url. For example:
1 |
index.php?page=contact |
In this case you should just read the request parameter just before the switch part, for example using:
1 |
$page = htmlspecialchars($_GET['page']); |
You can also add a bit more assurance and say threat the default
section as something invalid / invalid request or bad request in case someone wanted to do something the code should not expect.
That’s about it, happy codding.