They all import code from that PHP file, but what's the difference between using include () or require ()? Do I have to use include () or include_once ()?
require() vs include()
Both functions import or insert the code contained in the .php file into another. The difference can be deduced from its name:
require () establishes that the code of the invoked file is required, that is, mandatory for the operation of the program. Therefore, if the file specified in the require () function is not found, a "PHP Fatal error" error will be thrown and the PHP program will stop.
include (), on the other hand, if the code is not found, a "Warning" error will be thrown and the program will continue running (although as a consequence of not including the code it may not work correctly, or yes, it depends on the situation).
Therefore, it is more common to use require (), because the most normal thing is that if we call the code of another file it is because we need it. However, require is usually used to invoke code that, if it is not included, the program can reach very serious errors and therefore, in these circumstances, it is better to stop the execution of the program. And use include () to call files whose code does not affect other parts of the application and, therefore, if they are not, will not affect the rest of the program.
For example, if we have a PHP script to show articles it would be better to use require (), to load the code that makes the query to the database and receive the data of the article to be displayed, while we can use include () to invoke the file that contains html code such as the footer of the web page or another part of the template.
require_once()/include_once() vs require()/include()
The require_once () and include_once () versions work in the same way as their respective versions, except that, when using the _once version, the loading of the same file is prevented more than once.
If we include the same code more than once, we run the risk of redeclarations of variables, functions or classes. It is logical to think that because of this, it is always better to use the _once version. However, you should know that these versions are heavier and consume more resources and therefore must be used only when necessary.