A PHP include is used when you want to include the contents of one file inside another...a very useful command!
<?php include("file.inc"); ?>
Real World Usage for Includes
Let’s say you are developing a 5 page website that you might be adding pages to. Your navigation HTML looks like this:
<html>
<head>
<title>My Navigation</title>
</head>
<body>
<a href=http://www.yourwebsite.com/index.php>Home</a>
<a href=http://www.yourwebsite.com/products.php>Products</a>
<a href=http://www.yourwebsite.com/articles.php>Articles</a>
<a href=http://www.yourwebsite.com/blog.php>Blog</a>
<a href=http://www.yourwebsite.com/contact.php>Contact Us</a>
</body>
</html>
...and this is going to be in every page. Now, when you add a page to your website, you are going to have to change the code on all 5 pages to reflect the new link. This could take several minutes to do...and what if the site expands to 20 pages or more? It’s going to be a nightmare!
PHP Includes to the rescue!
Let’s cut the menu link code out of the example above and paste it into a new plain text document (You can use Notepad on Windows or TextEdit on the Mac for this).
<a href=http://www.yourwebsite.com/index.php>Home</a>
<a href=http://www.yourwebsite.com/products.php>Products</a>
<a href=http://www.yourwebsite.com/articles.php>Articles</a>
<a href=http://www.yourwebsite.com/blog.php>Blog</a>
<a href=http://www.yourwebsite.com/contact.php>Contact Us</a>
Save this text file as navigation.inc. Paste the following in place of where the code was in the original HTML files..
<?php include "navigation.inc" ; ?>
Then save the HTML page as a PHP page. Voila! Any time you need to change the menu links, all you have to do is edit one file - the navigation.inc file!
A Note on Includes...
You don’t have to use .inc as the extension for an include - you can include almost any type of file with a PHP include - HTML, PHP, even other URL’s! One thing to keep in mind, however...is to strip out all the formatting code from the page you are including from (like the <html> and <body> tags). In other words, only include exactly what you need!
0 Comments
|
David Rentson
If this free PHP and MYSQL Tutorial is helpful for you... Great! Archives
October 2008
Categories
All
|