Simplify Your Website with PHP Includes

12.11
2013

By Aaron In Tutorials


Do you prefer YouTube? Watch the video here.

When I got started with PHP, the very first thing that I learned was “Includes”. There are numerous ways of accomplishing this task, in multiple other languages such as ASP.net, etc. Since I primarily use PHP and a few requests have come in asking for PHP lessons, I thought this would be a great start. It is still one of my all-time favorite elements to PHP.

Please understand that PHP is a very complex language and this will only barely start to scratch the top-most part of the surface.

Before we start, you’ll want to make sure that you’re using .php files, rather than .html files. This is really as simple as changing the file extension of your files from .html to .php. If you’re starting with new files, just save them as .php files.

What are ‘Includes’?

‘Includes’ are simply chunks of code from your website that are used in multiple places or pages, that can be externalized and plugged back into your site. It works  similarly to how an external CSS file works.

Includes are external like CSS

In our example, we’re using it for a Navigation Menu, which would be the same on each page. We will take the HTML code for the menu, remove it and add it into its own file.

We’ll add this into a .php. I’ve called mine nav-main.php and saved it into a sub-folder called /includes.

Once we’ve added our HTML into the nav-main.php include file, we can add it anywhere into our site with a PHP tag.

This will add the chunk of HTML code into our main website.

The beauty of this is that we only have one source file to edit if we need to make changes. Let’s say that we need to add another page to our website, we only need to change the navigation once, rather than on every single page. Also, since we’re now using PHP files, you can incorporate other PHP code into these files to add more advanced features.

Where else do you think this could be useful? Share your ideas in the comments below!

 

VIP List

Join The VIP Mailing List

Even if you don't visit this site on a regular basis, you can
get the latest posts delivered to your inbox.

I hate SPAM. I value your privacy and trust.


Leave Us Your Thoughts