PHP Tutorial 10 | Using External File Includes
5 November 2007 - 3:57
Now that you know the basics of PHP we can begin the process of creating an actual website! If you have much experience with HTML you may have heard of Server Side Includes (SSI). Essentially server side includes are a way to create headers, footers, scripting statements, or other elements that can be reused (or included) on multiple pages.
In PHP there are four functions that you can use to call external files and include them in your page. Those are:
include()
include_once()
require()
require_once()
Using Include()
As you can imagine, include() includes an external file in your php script. To demonstrate how this works imagine we have three files.
The first is a header.inc file which contains a basic h1 header for the page:
<h1>Using External File Includes</h1>
The second a footer.inc file containing a paragraph of contact information:
<p>contact us at info@thedesignjunkie.com</p>
You can imagine where we are going with this
Now, in our PHP file (page1.php) we want to include the header and the footer files. The page code would look something like this:
<html>
<head>
</head>
<body>
<?php
include 'header.inc';
?>
<?php
include 'footer.inc';
?>
</body>
</html>
Load all three files to the same directory and call up the PHP page in your web browser and you get:

Looking at the source code or the document you’ll notice that you don’t see any PHP script. All you see is the HTML code.
Using Require()
Require() behaves just like include() except if for some reason the file requested does not load the require() function will kill the entire script and you will get an error message. Using include() you don’t get this. For this reason I suggest using include() for cosmetic includes and require() when you have an include that is more important. Essentially, you should use require when you want the entire script to stop if the include is not found.
Include_Once() and Require_Once()
Just like include() and require(), the include_once() and require_once() functions are used to include headers, footers, scripting statements, or other elements that can be reused (or included) on multiple pages. The only difference is that with the ending _once() the functions are only called one time.
No Comments | Tags: PHP, Uncategorized

Loading ...