PHP : Include Files

Including files in PHP is a powerful way to reuse code, separate concerns, and improve code organization. There are a few ways to include files:

1. include:

The include statement includes and evaluates a specified file during the execution of the script. If the file is not found or cannot be included for any reason, it will produce a warning but continue the script execution.


include 'header.php'; // Include header.php file
include 'footer.php'; // Include footer.php file

 

2. require:

The require statement is similar to include, but it produces a fatal error if the specified file cannot be included. It halts the script execution if the file is not found.


require 'config.php'; // Require config.php file
require 'functions.php'; // Require functions.php file

 

3. include_once and require_once:

These statements work similarly to include and require, respectively, but they only include the file once. If the file has already been included, it won't be included again.


include_once 'header.php'; // Include header.php file only once
require_once 'footer.php'; // Require footer.php file only once

 

Example:

Let's say we have two files: header.php and footer.php.

header.php:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <header>
        <h1>Welcome to my website</h1>
        <nav>
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </header>

 

footer.php:

    <footer>
        <p>&copy; <?php echo date("Y"); ?> My Website</p>
    </footer>
</body>
</html>