Using an include file for footer links with PHP

Posted in PHP -

I was asked an interesting question by email over the weekend and thought I'd share my response here. The question was "I wish to include in the footer links to my other developed websites. I don't wish to update the footer on each html page every time I create a new webpage. What would be your advice for implementing something like that using html, js and css".

Client-sided vs server-sided

The question asked about using Javascript as well as HTML and CSS and didn't mention a server-sided programming language at all. While it is possible to write out the footer links using Javascript from a common JS file, I wouldn't recommend it.

Apart from just feeling a little bit of a "hacky" way to do it, there are SEO advantages from having the links actually coded into the HTML of the page; if they're written out in Javascript search engines are unlikely to follow your links and assign weight to them etc.

Making static HTML files dynamic with PHP and Apache

Making the assumption that the files are a bunch of static HTML files, I suggested that if the site is hosted on a server that supports PHP then to make the regular HTML files be parsed as PHP, which I have shown how to do in my "get Apache to parse .html files as PHP" post.

Use include() to include the footer file

Now that the files are being parsed as PHP you can add blocks of PHP code to the HTML files. Nothing needs to be done to them to make this work, and even if there is no PHP in the files they will still be served as they are sending the existing HTML to the web browser.

At the appropriate place in the each HTML file, add the following tag, where 'footer-links.html' is the name of the file that contains the footer links:

<?php include('footer-links.html'); ?>

Then add links to the file, add stlying to it with CSS etc etc.


Ideally you really don't want your site to be a bunch of static HTML files because it makes updating the site structure etc in the future much more difficult, but if that's what you are stuck with then this is an easy enough to implement solution.

It's a bit quick and dirty but it means the links will be served in the HTML itself and maybe you can at the same time think about changing your site over to a more structured system with separation of content and template.

Related posts: