PHP Include and Require

PHP Include and Require

In PHP, you can insert the content of one PHP file into another PHP file before the server executes it. This is a core component of building scalable web applications!

The include and require statements are used to create standard components (like headers, footers, or navigation menus) that can be reused across multiple pages.


The Power of Reusability

Imagine you have a website with 50 pages. If you hardcode the navigation menu into all 50 files, updating a single link means modifying 50 different files!

Instead, you can write the navigation menu once in a file called menu.php and include it on every page. When you need to update the menu, you only change one file.

<html>
<body>

<!-- Including a standard menu --> <?php include 'menu.php'; ?>

<h1>Welcome to my home page!</h1>

</body> </html>


include vs. require

Both include and require do the exact same thing: they pull code from another file. However, they handle errors very differently.

When to use which?

Use require when the file is absolutely crucial to the application (like a database connection file or core configuration). Use include when the file is not strictly necessary and the application should continue running even if it fails to load (like an optional sidebar widget).


include_once and require_once

Sometimes, in complex applications with multiple included files, you might accidentally include the exact same file twice. This can lead to "Function already declared" errors.

To prevent this, PHP offers include_once and require_once.

Require Once Example

<?php
// This file will be included
require_once 'config.php';

// PHP will ignore this second request to prevent duplicate code require_once 'config.php';

echo "Configuration loaded safely!"; ?>


Exercise

?

If a required file is missing, what does the require statement do?