Using PHP Includes

When you use divs or tables for a layout, it gets really annoying if you have to copy and paste your layout code onto every page. Just like with CSS, we can make large chunks of HTML coding show up on every page using one simple line, and it's not even that hard! The problem most people have is wrapping their head around how the includes work. Just like their name suggests, these short codes allow you to INCLUDE large areas of coding. But once you get the general idea of it, then the rest should come fairly easily! So let's get started.

Ok, let's say your regular page coding looks like this:


<html>
<head>
<title>My Page!</title>
<link href=" style.css" rel="stylesheet" type="text/css">
</head>
<body>

<div id="nav">
<a href="main.php">Home<br><a href=" me.php">Me</a>
<br><a href="you.php">You</a>
<br><a href="site.php">Site</a>
</div>

<div id="main">
Hey there! Welcome to my site!!
//Content goes here
</div>

</body>
</html>


This is just really basic coding- nav on the left, content on the right. Usually with PHP you use FULL URL's, just so there's no confusion and you don't get errors. Now, when you split this up, you're going to split it into header.php, footer.php, and your main. EVERYTHING before your actual content goes into header.php, EVERYTHING after your content goes into footer, then your actual page is just really plain, with some includes:

In this case, header.php would look like:


<html>
<head>
<title>My Page!</title>
<link href=" style.css" rel="stylesheet" type="text/css">
</head>
<body>

<div id="nav">
<a href="main.php">Home<br><a href=" me.php">Me</a>
<br><a href="you.php">You</a>
<br><a href="site.php">Site</a>
</div>

<div id="main">


It includes your nav, so that if you want to change something in your navigation, you don't have to do it on every page. Then footer.php would look like this:


</div>

</body>
</html>


Footers are usually really short, but you can also add in your copyright, or, if all your navigation's on the right of your content, it would go in your footer, instead.

And then your main page would look like this:


<?
include("header.php")
?>

Hey there! Welcome to my site!!
//Content goes here

<?
include("footer.php")
?>


Then, every page after that would look similar to this one. Every page you make with these includes will look exactly the same except for the actual content you type on them. This makes layout changes SOOO much easier, because you just need to change your header and footer files, then ignore everything else! I usually start by coding a full layout with some fake content in it, then copy and pasting my header and footer into separate files, instead of piecing them together separately. That way, I know that it's going to work when it's all back together in one page. I hope this helps! As I said before, PHP includes make coding and changing layouts a lot easier, especially if it's a long code. I hope this helps you out!