HOME HTML EDITOR C JAVA PHP

PHP Include and Require

The include and require statements allow you to insert the content of one PHP file into another PHP file before the server executes it. This is perfect for creating reusable elements like navigation bars, headers, or footers.

1. The Basic Syntax

Both statements are used similarly:

include 'filename';
// OR
require 'filename';

2. Why use Include/Require?

Imagine you have a website with 50 pages. Instead of writing the same HTML code for the menu on every page, you can write it once in a file named menu.php and include it like this:

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

If you want to change a link in the menu, you only need to update one file instead of 50.

3. Include vs. Require (The Difference)

The difference lies in how the script handles a failure (e.g., if the file is missing):

Statement Behavior on Error Usage
include Produces a Warning (E_WARNING) but the script continues to run. Use for non-essential items like footers.
require Produces a Fatal Error (E_COMPILE_ERROR) and the script stops immediately. Use for essential items like database connections or security checks.

4. include_once and require_once

If you accidentally include the same file twice, it might cause errors (like declaring the same function twice). To prevent this, use the _once version. It checks if the file has already been included; if so, it will not include it again.

<?php
  require_once 'config.php';
  // This ensures the configuration is only loaded once.
?>
Best Practice: Use require for files that are vital to the application's flow (like database settings) so that the application crashes immediately if something is wrong, rather than running with missing data.