Include and Require

Have you ever written some HTML code that was exactly the same across multiple pages, like a header or a footer? Your life is about to get so much easier. These awesome creatures known as PHP Server Side Includes will save you so many headaches and keystrokes later.

It is generally good practice to use the include function when writing code, and then later as you review it to replace it with the require function. Based on their overall purpose, they do exactly the same thing. They both “include” a file such as another PHP file that includes a standard header for your website. This is entirely like writing it out manually on each page. However, the difference between the two functions is that the require function stops executing your code as soon as an error occurs. The include function would still continue executing. Running the rest of the code after an error is usually not a good idea, so use require.

Using Include and Require

Example

Result

HTML Text

PHP Text

How freaking cool is that? You can completely put a navigation menu in a file and reference it using a require. I put PHP code and HTML code in my include to show you that it really doesn’t matter. You can include simple HTML files, PHP files, or a crossbreed of them. You can now require headers, footers, navigation bars, and anything else you don’t want to type more than once.

Let me just say a small precautionary note really quick. Don’t go too overboard. I have worked on various sites where I had to go through the requires of 6 pages to correct an error. Try to just have includes for the header, footer, navigations, and a few files with commonly used functions.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

Leave a Reply

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