There are 4 ways to include a file on your page. They are:
1. PHP include Function: The PHP “include” function is used in PHP when you want to include a file within the current process.
i. It takes one argument which will be a string to the file path you want to include.
ii. The code inside the included file will then run when the include function is called.
iii. This can be used in PHP templates where you have a header at the top of the page and the header is going to be the same on all pages.
iv. You will put this code inside it’s own file and use the include function to add the file to the page.
v. If the file that you want to include is not found then this function to return a PHP warning, which is different to the require function which will return a fatal error.
vi. The file path given to the function can be either absolute starting with a / or relative by placing a “..” before the file.
2. PHP include_once Function: The “include_once” function is exactly the same as the include function except it will limit the file to be used once.
i. The PHP include function will allow you to include the same file multiple times so you can use it within a loop.
e.g.: (1) foreach
($products as $product)
// will display all products.php file as many times as it loops through the $product array
foreach($products as $product)
// will only display the product.php file once
ii. A more practical use of this function is if you define any functions in the included file to avoid redefinition of a function you should include it with a include_once.
3. PHP require Function: The “require function” acts just like the include function except if the file cannot be found it will throw a PHP error.
i. As the name suggests this file is required for the application to work correctly.
ii. This function throws a fatal error E_COMPILE_ERROR which will stop the application continuing, when the file is not found.
iii. The require function is used exactly the same as the include function.
4. PHP require_once Function: The PHP “require_once” is a combination of require and include_once function.
i. It will make sure that the file exists before adding it to the page if it’s not there it will throw a fatal error.
ii. It will make sure that the file can only be used once on the page.
iii. This function is the most strict out of the four functions
iv. The require_once function is what you should use when displaying things like the website header and footer. This is because you always want these files to be here if they are not here you want the site to error, and you only want these to appear once on the page.
<? <PHP code>?>