if you are reading my post you are here because you are probably wondering what are the differences between include() vs include_once() in PHP. When I started using PHP, I never thought much about it, but now the I am using PHP on a daily basis, I wondered what are the differences, so i will try to explain as simple as possible from a beginner like me.

well, I am going to try to explain.. this is the official explanation of include() vs include_once() per PHP.net:

Quote:
The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

Source: http://www.php.net/manual/en/function.include-once.php

OK, what does this mean exactly? lets say for example, i have three files,

FILES:

FUNCTIONS.PHP
GLOBALS.PHP
HEADER.PHP



this is how each file looks like:

FUNCTIONS.PHP
<?php
function foo(){
echo 'some code';
}
?>


GLOBALS.PHP:
<?php
include('FUNCTIONS.PHP');
foo();
?>



HEADER.PHP
<?php
include('FUNCTIONS.PHP');
include('GLOBALS.PHP');
foo();
?>



now if you try to open HEADER.PHP you will get an error because GLOBALS.PHP includes FUNCTIONS.PHP already. you will get an error saying that function foo() was already declared in GLOBALS.PHP, and i also included in HEADER.PHP - which means i have included FUNCTIONS.PHP two times.

so to be sure i only include FUNCTIONS.PHP only ONE time, i should use the include_once() function, so my HEADER.PHP should look like this:

HEADER.PHP
<?php
error_reporting(E_ALL);ini_set('display_errors',1);
include_once('FUNCTIONS.PHP');
include('GLOBALS.PHP');
?>


now when i open HEADER.PHP, i will not get an error anymore because PHP knows to include the file FUNCTIONS.PHP only ONCE


so to avoid getting an error, it would just be safe to use include_once() instead of include() function in your php code.

if you know you are messy with your PHP code, then its safer to use the include_once(), but if you keep track of all your code, then its ok to use the include() function.

hope i helped you explained the differences between the include() and the include_once() functions in php

UPDATE: Thanks for all your comments.. I see that some of you are not getting errors. this is because your PHP configuration is set not to show errors. I have added this line to the HEADER.PHP file so it will show you the error:
error_reporting(E_ALL);ini_set('display_errors',1);

for your convenience, i have attached the files i used to test this tutorial, you can download it and try it yourself.

Hope that helps

29-p1222-include-vs-include-once-wallpaperama.com.zip