PHP Include

The tutorial will help you learn about PHP Include.

 

The include() [or require ()] statement lets you include the code contained in a PHP file within another PHP file. It takes all the text/markup/code that exists in a particular file and copies it into another file that uses the include statement. This function is very helpful if you want to include the same PHP, HTML, or text on multiple pages of a website.

 

PHP include and require Statements

Using the include or require statement, you can insert one PHP file's content into another PHP file (before the server executes it).

 

The include and require statements are similar except upon failure:

  • include statement will only produce a warning (E_WARNING), and the script will continue.
  • require statement will produce a fatal error (E_COMPILE_ERROR) and stop the script

 

So, in case you want the execution to go on and show users the output, even in case the include file is missing, you can use the include statement. However, in the case of CMS, FrameWork, or complex PHP coding, you should always include the require statement for including a key file to the flow of execution. It helps ensure your application's security and integrity if one key file is accidentally missing. 

By including files, you can save a lot of work. A standard header, footer, or menu file can be created for every web page. When you need to update the header, you can only update the header include file.

 

Syntax

include 'filename';

or

require 'filename';

 

Example:

<html>
<body>

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

</body>
</html>

footer.php

<?php
echo "<p>Copyright &copy; " . date("Y") . " yourwebsite.com</p>";
?>

 

PHP include vs. require

You can also use a require statement for including a file into the PHP code.

The major difference between include and require is when a file is included with the include statement and PHP is unable to find it; the script will continue to execute:

<html>
<body>

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

</body>
</html>

Using a require statement in the same example, it will not execute the echo statement because the script execution will die after the require statement returns a fatal error:

<html>
<body>

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

</body>
</html>

 

Note:-

  • It is recommended to use require when the application requires the file.
  • It is recommended to use include when the file is not required, and the application should continue when the file is not found.