Site icon

PHP include() Vs require()

Securing PHP Page Access

Let’s see what’s the difference between PHP include() Vs require(). In this tutorial, we are going to see the list of functions used in PHP to include an external file into a program. PHP provides various functions to include external files.

The following list of functions is used to include an external file into a PHP program. We are going to see the purpose of the _once usage and the difference between include and include_once/require and require_once.

include():
PHP include() function includes external file into a PHP program. It accepts the external file path and checks if the file exists or not. If the file does not exist in the specified path, then the include() will return PHP warning. include() function can be used in loops or control structure.

Warning: failed to open stream: No such file or directory…
Warning: Failed opening … for inclusion…

By including an external file by using the PHP include() function, the variable, functions, and classes of the included file can be used in the program where it is included. The following code shows an example for including an external file using PHP include().
[pastacode manual=”%3C%3Fphp%0D%0Ainclude(%22..%2Ffile_name.php%22)%3B%20%2F%2F%20relative%20path%0D%0A%2F%2FOR%0D%0Ainclude(%22https%3A%2F%2Fwww.website.com%2Ffile_name.php%22)%3B%20%2F%2F%20absolute%20path” provider=”manual” lang=”default”/]
If we include the same file multiple time by using this function, then it will cause a PHP error.

require():
PHP require() function is as similar as include() function. But, the difference is, the require() function will return a fatal error and stop executing the program at the time of failure where the include() function returns warning and continue execution. require() function can not be used in loops or control structures.

Warning: failed to open stream: No such file or directory…
Fatal error: Failed opening required…

The code to include file using require() function is,
[pastacode manual=”%3C%3Fphp%0D%0Arequire(%22..%2Ffile_name.php%22)%3B%20%2F%2F%20relative%20path%0D%0A%2F%2FOR%0D%0Arequire(%22https%3A%2F%2Fwww.website.com%2Ffile_name.php%22)%3B%20%2F%2F%20absolute%20path” provider=”manual” lang=”default”/]
PHP include() Vs require()

include_once() and require_once():

The include_once() and require_once() functions are similar to the include() and require() functions, respectively. But, using this function will create difference at the time of including the same file for multiple time. By using include_once() and require_once() functions, will include the specified file if it’s not already included, otherwise, PHP will ignore this statement. The code is,
[pastacode manual=”%3C%3Fphp%0D%0Ainclude_once(%22..%2Ffile_name.php%22)%3B%20%2F%2F%20relative%20path%0D%0A%3C%3Fphp%0D%0Arequire_once(%22..%2Ffile_name.php%22)%3B%20%2F%2F%20relative%20path” provider=”manual” lang=”default”/]

Exit mobile version