agyanadda@gmail.com

PHP include and require

PHP Forms and Web 1 min read Updated Dec 1, 2026 Topic 24 of 36

Split your site into reusable files — write the header once, use it on every page.

<?php require __DIR__ . '/partials/header.php'; ?>
<h1>About us</h1>
<?php require __DIR__ . '/partials/footer.php'; ?>

The four statements

Statement If the file is missing Loads twice?
include warning, page continues yes
require fatal error, page stops yes
include_once warning no
require_once fatal error no

Use require (or require_once) for important files like config and functions. Use include for optional parts.

Use DIR

__DIR__ . '/config.php' always finds the file, no matter which page includes it.

Return values

A config file can return an array:

// config.php
return ['db_name' => 'school', 'gst' => 18];

// index.php
$config = require __DIR__ . '/config.php';

This is how Laravel's config/ folder works.

Example

Example — Header, footer and config files PHP
<?php
// ---- config.php ----
return [
    'site_name' => 'AgyanAdda',
    'phone' => '+91 98xxxxxx10',
];

// ---- partials/header.php ----
// <header><h2><?= $config['site_name'] ?></h2><nav>Home | Tutorials | Contact</nav></header>

// ---- partials/footer.php ----
// <footer>Call us: <?= $config['phone'] ?> · © <?= date('Y') ?></footer>

// ---- about.php ----
$config = require __DIR__ . '/config.php';
$pageTitle = 'About us';
require __DIR__ . '/partials/header.php';
echo "<h1>$pageTitle</h1><p>We teach coding in simple language.</p>";
require __DIR__ . '/partials/footer.php';

This example spans four files. about.php shows the shared header, its own content and the shared footer. Change the phone number in config.php and every page updates.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which statement stops the script with a fatal error if the file is missing?

Exercise 2 True / False

require_once loads a file only one time, even if called again.

Exercise 3 Fill in the Blank

Use the magic constant ___ to build reliable include paths.

Frequently Asked Questions

It is disabled by default (allow_url_include) because it is a big security risk. Only include files from your own project.