BEGIN TYPING YOUR SEARCH ABOVE AND PRESS RETURN TO SEARCH. PRESS ESC TO CANCEL

Learn PHP: Class Three, Includes and Requires

Today we are going to learn all about include and require! Include and require are handy to use not only in your php applications, but in general website design for sidebar’s and what not! So.. yeah.. 😛 Moving on!

Include and Require include a file within another PHP script. There are four ways of doing this:


include();
include_once();
require();
require_once();

Now using them is seriously simple. Lets say you have a file called “sidebar.php” with your links? All you have do do is the following:

include('sidebar.php');

One thing to remember is how to traverse directories in PHP. For instance, if my file “sidebar.php” is in a folder called “includes” you could go:

include('includes/sidebar.php');

Or another approach, if my file “sidebar.php” is in the parent directory, you could go:

include('../sidebar.php');

Now why are there four different ways to include them I hear you ask! Well they are pretty simple.

Include and Require are practically the same, apart from the way they give out errors. Include will continue parsing your script and just shove out an error. Require however will stop the whole script to give you an error. Really it’s all down to what you want.

Include_once and require_once you probably guess only allow you to include the file once. This is not only more secure but stops from silly errors where the file was just included and variables were overwritten halfway through the script. Again they give out the same errors as include and require.

So lets go over one of each!

include('sidebar.php');
include_once('sidebar.php');
require('sidebar.php');
require_once('sidebar.php');

We really are spoiled for choice aren’t we! 😉

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.