PHP Include Files

In PHP, you can include another file in a single file. If you are implementing a functionality that is common in most of your project files, then you do not need to implement it separately in every file.

PHP’s include statement includes and executes the specified file. The file you want to include is specified in single quotes. This statement can not only include PHP file but also HTML and text file.

When a file is included in another file, the include statement is replaced by the contents of that file. When a file is not successfully included, FALSE is returned and a warning is performed. 1 return is done when the file is successfully included.

Syntax

include 'filename';

Example 1

<html>
<body>

<h1>Welcome!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

Example 2

<html>
<body>

<div class="menu">
<?php include 'menu.php';?>
</div>

<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>

PHP Require Statement

The PHP require statement also works just like an include statement. Through this statement, you can also include a PHP, HTML or text file in another file. The syntax of these two statements is also the same.

The only difference is that when the need statement fails to include a file then the error is generated and script processing is stopped.

Syntax

require 'filename';

Example 1

<html>
<body>

<h1>Welcome to my home page!</h1>
<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Example 2

<html>
<body>

<?php
echo “<h1>PHP require Statement Demo</h1>”;
// Including other file in current PHP file with necessity mode.
require ‘first.php’;
?>

</body>
</html>

PHP Include vs. Require

If you are including a file which you do not want to properly include when you want to stop processing then you need to use the require statement. If you do not want to continue processing your application even if you are not included in the file, you should use the include statement.