PHP Tutorial Tutorials - PHP Include and Require Files

PHP Include and Require Files

Include takes a file name and simply inserts that file's contents into the script.
We can save a lot of time using include files -- store the block of common code in a separate file and reuse it in many PHP scripts.
There are two ways to include file in php:

  • include() and include_once()
  • require() and require_once()

PHP include files Example

include() and require() statement syntax

include("path/to/filename"); // You can use relative or absolute path.
// OR
include "path/to/filename";

require("path/to/filename"); // You can use relative or absolute path.
// OR
require "path/to/filename";

A typical example is including the header, footer and menu file within all the pages of a website.
main.php

<?php
    include("header.php");
    echo "<h3>the main page</h3>";
    echo "<p>Main Content</p>";
    include("footer.php");
?>

menu.php

<a href="http://www.lautturi.com/about.php">About Us</a> | 
<a href="http://www.lautturi.com/links.php">Links</a> | 
<a href="http://www.lautturi.com/contact.php">Contact Us</a>

header.php

<html>
<body>
<?php
    include("menu.php");
?>

footer.php

<p>© 2017 Lautturi.com Privacy and Cookies</p>
</body>
</html>

It's just simply insert the file's contents into the script.So at the runtime,the content of main.php just like:

<html>
<body>
<a href="http://www.lautturi.com/about.php">About Us</a> | 
<a href="http://www.lautturi.com/links.php">Links</a> | 
<a href="http://www.lautturi.com/contact.php">Contact Us</a>
<?php
    echo "<h3>the main page</h3>";
    echo "<p>Main Content</p>";
?>
<p>© 2017 Lautturi.com Privacy and Cookies</p>
</body>
</html>

PHP include vs PHP require

Difference Between PHP include() and PHP require()

If there is a failure when include files(e.g the file is missing),
include() only emits a warning (E_WARNING) which allows the script to continue.
whereas require() will produce a fatal E_COMPILE_ERROR level error and halt the script.

PHP include_once() and PHP require_once()

As Mentioned Previously,Include files is just simply insert the file's contents into the script during the execution of the script.
If you accidentally include the same file more than one time,It may cause function redefinitions,variable value reassignments,etc.
PHP provides include_once() and require_once() to avoid these problems.

include_once() and PHP require_once() are behaviors similar to the include and require statement.
The only difference is that: if the code from a file has already been included, it will not be included again.

inc.php

<?php
    function sum($num1,$num2){
        return $num1+$num2;
    }
?>

test.php

<?php
    include("inc.php");
    // include("inc.php"); // Fatal error: Cannot redeclare sum() (previously declared in inc.php:2)
    include_once("inc.php");
    $result = sum(3,2);
    echo $result;
?>
Date:2019-10-01 02:49:59 From:www.Lautturi.com author:Lautturi