w3resource logo


PHP require_once and include_once statement

PHP require_once(), include_once()

rating PHP require_once, include_once() statement has average rating 7 out of 10. Total 42 users rated.

<<PreviousNext>>

PHP require_once()

Description

require_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with require_once() statement, and does not find b.php, a.php stops executes causing a fatal error.

Syntax

require_once('name of the calling file with path');

Example :

<?php
echo "today is:".date("Y-m-d");
?>

The above file is x.php

The above file x.php, is included twice with require_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored,  since require_once() statement ignores all the similar inclusions after the first one.

<?php
require_once('x.php');
require_once('x.php');
?>

View this example in the browser

If a calling script does not find a called script with require_once statement, it halts the execution of the calling script.

PHP include_once()

Description

The include_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with include_once() statement, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php.

Syntax

include_once('name of the called file with path');

Example :

<?php
echo "today is:".date("Y-m-d");
?>

The above file is x.php

The above file x.php, is included twice with include_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored,  since include_once() statement ignores all the the similar inclusions after the first one.

<?php
include_once('x.php');
include_once('x.php');
?>

View the example in the browser

If a calling script does not find a called script with include_once statement, it halts the execution of the calling script.



We have compiled a number of PHP exercises. Check and assess you PHP skill by visiting those exercises.

<<PreviousNext>>