cPanel Reseller Tutorials – include() and require()
If you have ever looked at your website’s index.html or index.php code, you have surely noticed that there is really a lot of code there. And if you have a basic or no understanding of the scripting language used for the file, you will be looking at just some random letters, which speak nothing to you. Today, me and Kevin Johnson from the reseller support team join forces in trying to bring some light on some of the most simple and useful functions in the PHP scripting language – include() and require().
include() and require()
When building a website, a very simple rule applies to the website’s code – keep it simple. The more simple the code, the faster it will be read by the web server and served to the visitor. However, when you decide to add more functionality to the website, the code base grows and at some point you are faced with one huge file for each web page. And when the header, footer, or other parts of the web page repeat themselves, then you have to copy the same code over and over in every web page using it.
And here is where include() and require() come to the rescue. They allow you to have different files added into the file currently executed, acting as if they were a part of it. This allows you to divide your site into sections, each of them with just a few lines of code, instead of having one huge file.
At this point, you surely have noticed that there are two functions with the same functionality. While this is true, both functions are different from one another in the way they handle errors.
* include() generates a warning, but the script will continue execution
* require() generates a fatal error, and the script will stop
This is a major difference, so choose the function you will use wisely and always monitor the behavior of your script in the beginning, to make sure that it is running smoothly.
The most common usage for these functions, and the most important one, is to handle configuration files. The configuration files are files that keep all the important script information, such as admin username and password and database login credentials. Such files are usually given permissions, which restrict the access to them.
These functions can also be used when the file needing them is not written in PHP, but in HTML.
<?php include(“/path_to/config_file.php”); ?>
<?php require(“/path_to/config_file.php”); ?>
(* /path_to/config_gile.php- Should be replaced with the actual path to the configuration file which is above the /public_html folder *)Originally published Friday, July 24th, 2009 at 2:51 pm, updated July 26, 2009 and is filed under cPanel Support.