PHP include files
When you see a webpage, it seems that you are looking at a single file. This is only sometimes the case, and sometimes it is not. With the use of PHP's file inclusion functionality you can display a page that actually consists of several pages.
This tutorial focuses on:
- The purpose of including files
- The include() function
- The require() function
- The require_once() function
The purpose of including files
Including files can be very useful if all the pages (or many of them) on your website consist of the same parts such as the same header or footer. For example, if you have 30 pages that all have the same header and you need to change something in that header. If you have that header as part of the page in an include file, you can simply change that file and all the pages are updated automatically as opposed to updating each page manually.
The include() function
The include() function is used to include a file on a webpage.
So the page will display the above code at the top of it and right after that the message "Welcome to our site!" in a level 2 heading.
NOTE: Since PHP executes on the server-side, if the user were to look at the source code of a page that has PHP include files, they would only see client-side code and therefore would be under the impression that the page consists of one group of code. In the case of the above example, the developer of the site working on the code would see the code at the top of this paragraph. while a visitor who tries to view the source code of the page would see this:
The require() function
The require() function is very similar to the include() function with one major difference -- with the include() function, if a file that you try to include is not found, the rest of the script will be executed anyway, while with the require() function, if a file that you try to include is not found, the rest of the script will not be executed. The require() function requires files.
In the above example, the rest of the script was executed even though the file headerr.php was not found.
In the above example, the rest of the script was not executed because the file headerr.php was not found.
Is it better to use include() or require()?
It is better to use require() because scripts should not be executing if necessary files are missing.
The require_once() function
A third function used to include files is the require_once() function. The require_once() function behaves the same way as the require() function with one difference -- the require_once() function allows the contents of a file to be included only once.
What happens if you try to include the same file twice or more using the require_once() function?
The data from the file will be displayed only once.