Repasos Inglés

Include files in PHP code


As we move forward with the code examples in PHP, there is the possibility that our files will grow considerably and it will be very difficult to manage changes in the future.

Features to include files

You can include the content of one file within another through the following functions:
1. include.
2. require.
3. include_once.
4. require_once.
Although all the functions have the same purpose of including files within our code, each one has a specific use.

Include function

This function will try to find and include the file every time it is used in the code. PHP will display a warning if it cannot find the file, but will continue executing the code.

Function "require"

This function, like "include", will search and include the file that we specify, but instead of showing a warning when the file is not found, it will display an error and the program execution will be interrupted

Function "include_once"

This function performs the same action as the “include” function, but with the difference that it will only include the file the first time it is called. New calls to include the same file will be ignored.

Function "require_once"

This function performs the same action as the "require" function, but with the difference that it will only include the file the first time it is called. New calls to include the same file will be ignored.

Sample code to include files

In the following example we have used the “require” function to include four files that make up the structure of a web page, in this case, the header, menu, content and footer.
This is a very convenient way to separate chunks of code and also to reuse functions or file content.

<?php 

require 'header.html';
require 'menu.html';
require 'content.html';
require 'footer.html';