Introduction to PHP - Include and Require Statements

Guest Posts Paolo Nikko Nuñal

In PHP, letting you include files can be done thanks to the include and require statements. This is one useful statement as this is useful if you have a template header, footer or sidebar that you wish to include but don't want to write the code all over and over again.

The include and require statements are identical except during a failure.

The require statement will produce a fatal error (ECOMPILEERROR) and stops the script, compared to the include error that produces a (E_WARNING) and continues to load the script.

Here's how you do it.

<?php
   include 'header.php';
?>

or
<?php
   require 'header.php';
?>


Here's a sample implementation.

header.php

<html>
<head>
   <title>Dashboard</title>
</head>
<body>
   <div class="header">
        WELCOME USER
   </div>


footer.php

<div>
   <span>@Copyright 2014</span>
</div> 
</body>
</html>


Supposed that we have two files named header.php and footer.php. Since most websites change only the content and not the header and footer, it is best to just include them.

body.php

<?php include 'header.php' ?>
<div>
   <p>The quick brown fox jumps over the lazy dog</p>
</div>
<?php include 'footer.php'; ?>


From the code above I've just included the header.php and footer.php on the specific parts of my body.php code. After which when it loads it will be a complete web page. It is not limited just to include html files but also you can include classes, variables and just about anything. Just consider the include and require statements as a way of "copy and pasting" a code.