Tuesday, August 12, 2008

PHP Include

Without understanding much about the details of PHP, you can save yourself a great deal of time with the use of the PHP include command. include takes a file name and simply inserts that file's contents into the script that issued the include command.

Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu file that you want all your web pages to include. When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.


An Include Example

Say we wanted to create a common menu file that all our pages will use. A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu let's save it as "menu.php".

menu.php Code:
< html>
< body>
Home -
About Us -
Links -
Contact Us


Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as "menu.php". Here we will take advantage of the include command to add our common menu.
index.php Code:


This is my home page that uses a common menu to save me time when I add
new pages to my website!


< /body>
< /html>

And we would do the same thing for "about.php", "links.php", and "contact.php". Just think how terrible it would be if you had 15 or more pages with a common menu and you decided to add another web page to that site. You would have to go in and manually edit every single file to add this new page, but with include files you simply have to change "menu.php" and all your problems are solved. Avoid such troublesome occasions with a simple include file.
What do Visitors See?

If we were to use the include command to insert a menu on each of our web pages, what would the visitor see if they viewed the source of "index.php"? Well, because the include command is pretty much the same as copying and pasting, the visitors would see:
View Source of index.php to a Visitor:

< html>
< body>
Home -
About Us -
Links -
Contact Us

This is my home page that uses a common menu to save me time when I add
new pages to my website!


< /body>
< /html>

The visitor would actually see all the HTML code as one long line of HTML code, because we have not inserted any new line characters. We did some formatting above to make it easier to read. We will be discussing new line characters later.

No comments: