Why PHP Include is Awesome!

PHP was the first backend web language I learned. Now while a lot of people may give PHP a bad rap here is the reason why I love PHP. 

<php include(example.html); ?>

This line of code in all its beauty and wonder is why I love this language so much. PHP include allows you to import other files into your HTML.


So whats the big deal?

If you are familiar with the concept DRY (Don’t Repeat Yourself), PHP include allows you to code once and populate everywhere. Here is an example:

Say you have a basic webpage with five or ten pages and each page has a structure like this.

<html>

<head>

<title>My awesome website!</title>

</head>

<body>

 <nav>

<ul>

<li>Link #1</li>

<li>Link #2</li>

<li>Link #3</li>

</ul>

</nav>

<p>Some awesome website text.</p>

<p>More awesome text!</p>

</body>

</html>


If you wanted to add a new link to your header you will have to add that link to each page. So that means you will need to edit every file that has that navigation on it.

Here is how PHP can help, for a simple scenario lets replace our navigation code with: 

<php include(nav.html); ?>

so now our page template should look like this (do this for each page).  Be sure to encapsulate PHP code with the proper tags.

<html>

<head>

 <title>My awesome website!</title>

</head>

<body>

 <php include (‘nav.html’); ?>

<p>Some awesome website text.</p>

<p>More awesome text!</p>

</body>

</html>

Create a new file (nav.html), and let's add back our links. So our nav.html should look like this:

<nav>

<ul>

<li>Link #1</li>

<li>Link #2</li>

<li>Link #3</li>

</ul>

</nav>


Upload these files and if all goes well … nothing should have changed!


Wait why did I do this if nothing changed?

Visually nothing has changed but here is where the magic of PHP include comes in. To add a new item to your navigation add this one line of text to your nav.html file. 

<nav>

<ul>

<li>Link #1</li>

<li>Link #2</li>

<li>Link #3</li>

<li>Link #4</li>

</ul>

</nav>

Push this update to your server and presto! Your change should be visible on every page that has include (nav.html);. 


Generally speaking today many people will not need to worry about this because a lot of content management systems do something like this already. But with PHP include hopefully, you can see how this little statement can be really helpful in managing your code and staying consistent. 

Hey, I’m Misha, a web developer from Washington, DC. Hope you enjoyed this article! Feel free to read other posts, view my work, or say hello!