require and require_once in php – PHP require and require_once

require and require_once in php – In the previous topic you read about include, include_once, now we will learn about require and require_once. require and require_once are used to include the file.

However, PHP also has other functions such as include and include_once to include the file.

require , require_once , include , include_once all have their main purpose to include the file, but they have some difference which makes them different from each other.

Difference Between include And require :

By the way, both require, include include the file, but the biggest difference between these two is that if there is no file at the given location.

If so, include only generates warnings and continues script execution, while require generates fatal errors and terminates execution.

File : getinfo.php
[php]

[/php]

[php]
Warning: include(simple.php): failed to open stream: No such file or directory in C:\xampp\htdocs\getinfo\getinfo.php on line 3

Warning: include(): Failed opening ‘simple.php’ for inclusion (include_path=’C:\xampp\php\PEAR’) in C:\xampp\htdocs\getinfo\getinfo.php on line 3
Execution is continue

Warning: require(simple.php): failed to open stream: No such file or directory in C:\xampp\htdocs\getinfo\getinfo.php on line 6

Fatal error: require(): Failed opening required ‘simple.php’ (include_path=’C:\xampp\php\PEAR’) in C:\xampp\htdocs\getinfo\getinfo.php on line 6
[/php]

Now you must have understood what is the difference between include and require.

Difference Between require And require_once :

The biggest difference between require and require_once is that when we use require, it includes the file every time even if the same file is already included, due to which PHP generates a fatal error. When the file is included two or more times.

File : getinfo2.php
[php]

[/php]

See also :  code for upload image in php - How to Upload Files on Server in PHP?

File : getinfo.php
[php]

[/php]

[php]
Fatal error: Cannot redeclare getinfo() (previously declared in C:\xampp\htdocs\getinfo\getinfo2.php:4) in C:\xampp\htdocs\getinfo\getinfo2.php on line 5
[/php]

So in the example you can see how a fatal error was generated by repeatedly including the same file.

Whereas if we use require_once to include the file, then no error will be generated even if the same file is included. Because require_once includes the file only if the same file has not been included before.

File : getinfo.php
[php]

[/php]

function inside getinfo2.php

I hope, now you must have understood the proper difference between require and require_once.

Leave a Comment