Including files makes it really easy to NOT duplicate code. It’s great for creating headers and footers for websites, or using it in the inverse: make the header and footer in one file, and include the content. You can also store site configuration files, functions, and repeating content, etc.
Function and Syntax
include(<file path>);
Manual Entry
http://php.net/manual/en/function.include.php
Notes and Use
Includes are a great way to include the same code to many different PHP files. I find this the most useful for storing variables and functions across an entire website. The other great way to use this function is to include repetitive code that needs to be outside of a function scope – for example: including form layouts across multiple pages. I like to use the same include for both my add and edit pages on a form sometimes.
Examples
Storing Site-Wide Variables
This is stored in the file ‘configuration.php’:
$blog_name = "jtGraphic.net"; $blog_description = "Ramblings of an Internet Addict";
This is another PHP file where you’re calling the include – call it whatever you want. I’ll call mine ‘main.php’:
include("configuration.php");
echo $blog_name."<br />";
echo $blog_description;
This is another PHP file somewhere else on the site – maybe inside the /content/ directory. Call it whatever you want. I’ll call mine ‘content.php’:
include("../configuration.php");
echo $blog_name."<br />";
echo $blog_description;
Both ‘main.php’ and ‘content.php’ will echo out the same information because you included the same file at the beginning of each.
Website Header and Footer
I find that another extremely powerful use of includes is to build your header and footer for your website. In this example, we’re going to dynamically set the title variable in the main content page and call it inside the include. This is how I build some of my simpler sites. By the way, this isn’t HTML standards compliant. It’s just an example.
We’ll call this file ‘header.php’
<html>
<head>
<title>jtGraphic.net <?php echo $page_title; ?></title>
</head>
<body>
/*snip*/
We’ll call this next file ‘footer.php’;
//snip
<div> © James Thompson and jtGraphic.net </div>
<body>
</html>
Now that we have our header and footer, we can make some more pages:
We’ll call this one ‘content_1.php’:
$page_title = "Some Title";
include("header.php");
//content here
include("footer.php");
We’ll call the next one ‘content_2.php’:
$page_title = "Some Other Title";
include("header.php");
//content here
include("footer.php");
When accessing ‘content_1.php’ and ‘content_2.php’ you should get everything you put in ‘header.php’ and ‘footer.php’, but the title should be what you defined in the content files. This is a really rudimentary example, but it is VERY useful.
Conclusion
So, remember: whenever you have a set of code that is duplicated you can probably deal with it through custom functions or includes. Don’t duplicate the code! If you have your own examples, feel free to link them up below!