Continuing on from Learn PHP: Ifs & Elses, we can start learning about including other files, which is very helpful for things like sidebars on your website etc.
Include and Require include a file within another PHP script. There are four ways of doing this:
Now using them is simple. Lets say you have a file called “sidebar.php” with your links? All you have do do is the following:
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:
Or another approach, if my file “sidebar.php” is in the parent directory, you could go:
Now why are there four different ways to include?
Include and Require are practically the same, apart from the way they give out errors. Include will continue parsing your script and just log an error. Require however will stop the whole script to give you an error. Really it’s all down to what you want.
require_once only allow you to include the file once. This is not only more secure but stops from 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!
Posted on September 16, 2009