I’d like to have the same header and footer on every page only with different contents using PHP. What is the best approach to do this?
I know of these two popular ones, but don’t know which of them (or maybe some others) to choose:
1. Include header and footer on every page
Into every page like contact.php, about.php, etc. you have to include header on top of the page and footer on the bottom. The content then goes between the too. For example contact.php would look like this:
<?php include("header.php"); ?>
Lorem ipsum dolor sit amet...
<?php include("footer.php"); ?>
When you want to do request, you just type example.com/contact.php
2. index.php?page=xyz
In pages like contact.php, about.php, etc. you store only the actual content. Then you have index.php with some parameter (e.g. page) by which you specify the content to be included. For example the contact.php file would look like this:
Lorem ipsum dolor sit amet...
And the index.php file like this (this is simplified version):
<html>
<head>
<title>Lorem ipsum</title>
</head>
<body>
<?php include(some_parser_function($_GET["page"].".php")); ?>
</body>
</html>
Now when you do request for index.php?page=contact it will show you index.php and between the opening and closing body tags the content from contact.php.
The first approach seems to me a bit unpractical, because you have to write the include functions into every page. In the second approach, if you want to have nice URLs like example.com/contact.php or just example.com/contact, you need to do apache mod_rewriting…
Which one of those (and others) approaches is better / more popular and why?
Thanks.
Option 2 is much better for templating. You can also use Rewrite to make this appear without have ?page=pagename at the end of the url. Also depending on how many pages you have on your site it is kind of a pain to have to do the two includes on every single file.
However if I were you I would look into using ob_start() ob_get_contents() and ob_flush(). Then you can actually run all the code on the included file before you start outputting html.
Here is an example:
This way you can easily create multiple templates to be used at any point. A template file would look like this: