Using PHP includes

Posted on March 5, 2009 by Ashley

PHP is a powerful language that has replaced HTML frames and JavaScript includes in performing the task of including code from one page onto another. Generally PHP includes are used for database connection scripts, functions or classes, to be included in dynamic pages. But they can also be used in your static html projects too.

This is really useful for including anything from a header, footer, menu or a script across multiple pages. If you then need to make a change to the header, footer, menu or script, then you only need to edit the included file.

How to use it

Its really simple to get started with includes. If you want to include a menu in your web project simply add the line of code below to your site pages.

<?php include ('includes/menu.php'); ?>

You then need to create the includes folder on your server and paste the following code or what ever script you want.

When you create the menu.php page there is no need to have the html doc type head and body script in there just your menu code, this is because php will include the complete file ‘as is’ and you will have two head and body tags.

<a href="http://www.papermashup.com/index.php">Home</a> /
<a href="http://www.papermashup.com/about.php">About Us</a> /
<a href="http://www.papermashup.com/links.php">Links</a> /
<a href="http://www.papermashup.com/contact.php">Contact Us</a>

So includes can be a great time saver when creating generic content throughout a site, this has been a simple introduction on how to get started using them.

This entry was posted in PHP, Tutorials and tagged , . Bookmark the permalink.
Comments
4 discussions around Using PHP includes
  1. Brian says:

    Wow, awesome, I have been using iframes! Much simpler lol

  2. Nick says:

    Isn’t it better to use require on db connects and that sort of thing?

  3. Ashley says:

    @nick The two functions are identical in every way, except how they handle errors. The include() function generates a warning (but the script will continue execution) while the require() function generates a fatal error (and the script execution will stop after the error).

  4. includes saves so much time updating your sites, I use then whenever poss.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribers
1,250
Twitter
510
Comments
1,207
Posts
125