0Pricing
PHP Academy · Lesson

Including and Requiring Files

Split pages into reusable parts with include and require.

Including and Requiring Files is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Code Reuse with File Inclusion

PHP provides four statements to include code from other files:

  • include — include file; warning if missing
  • require — include file; fatal error if missing
  • include_once — include only if not already included
  • require_once — require only if not already included

include and require

The key difference: a missing require file is fatal; a missing include just warns:

<?php
// Fatal error if missing — use for critical files
require 'config.php';
require 'database.php';

// Warning if missing, but execution continues
include 'optional_plugin.php';

// Use __DIR__ for reliable relative paths:
require __DIR__ . '/helpers/utils.php';

include_once and require_once

The _once variants prevent the same file from being included multiple times:

<?php
// Without _once: including twice redefines functions
include 'functions.php';
include 'functions.php';  // Fatal: function redefined!

// With _once: second include is a no-op
require_once 'functions.php';
require_once 'functions.php';  // safe — skipped

// Rule: use require_once for class and function definition files

Variable Scope in Included Files

Included files share the scope of the including file — but not function scope:

<?php
// main.php
$title = 'My Site';
require 'header.php';  // header.php can use $title

// But in a function:
function loadTemplate(): void {
    require 'header.php';  // $title is NOT accessible here!
    // Must pass data explicitly
}

Returning Values from Included Files

Include files can return values using the return statement:

<?php
// config.php content:
// return ['debug' => true, 'db_host' => 'localhost'];

// main.php:
$config = require 'config.php';
echo $config['db_host'];  // localhost

// Common pattern for configuration files that return arrays

Building a Simple Layout

Split a page into reusable header, content, and footer files:

<?php
// index.php
$pageTitle = 'Home Page';
$bodyClass = 'home';

require_once 'partials/header.php';
?>

<main class="container">
    <h1>Welcome!</h1>
    <p>Main content goes here.</p>
</main>

<?php require_once 'partials/footer.php'; ?>

Template Partials

Create reusable partial view files for repeated components:

<?php
// partials/card.php
// Expects: $card['title'], $card['body'], $card['url']
?>

<div class="card">
    <h3><a href="<?= htmlspecialchars($card['url']) ?>">
        <?= htmlspecialchars($card['title']) ?>
    </a></h3>
    <p><?= htmlspecialchars($card['body']) ?></p>
</div>

Passing Variables to Partials

Pass data to a partial via local variable assignment before including:

<?php
$articles = getArticles();

foreach ($articles as $article) {
    $card = [
        'title' => $article['title'],
        'body'  => substr($article['body'], 0, 100) . '...',
        'url'   => '/articles/' . $article['slug'],
    ];
    require 'partials/card.php';
}

include vs Autoloading

In modern PHP with Composer, class files are autoloaded — you don't manually include them:

<?php
// Old way (manual includes):
require 'classes/User.php';
require 'classes/Post.php';

// Modern way (Composer autoloading):
require __DIR__ . '/vendor/autoload.php';

// Classes are loaded automatically when first used
$user = new User();  // User.php loaded by autoloader
$post = new Post();  // Post.php loaded by autoloader

Security: Prevent Path Traversal

Never include files based on unvalidated user input:

<?php
// DANGEROUS:
$page = $_GET['page'];
include $page . '.php';  // allows ../../etc/passwd

// SAFE: whitelist allowed pages
$allowed = ['home', 'about', 'contact'];
$page = $_GET['page'] ?? 'home';

if (!in_array($page, $allowed)) {
    $page = 'home';
}

include __DIR__ . '/pages/' . $page . '.php';

include_path Configuration

Configure PHP's include_path so you can include files without full paths:

<?php
// Current include_path:
echo get_include_path();

// Add your library directory:
set_include_path(
    get_include_path() . PATH_SEPARATOR . '/var/www/lib'
);

// Now you can include without full path:
include 'helpers.php';  // found in /var/www/lib/helpers.php

Quick Check

What is the difference between include and require when the file is missing?

Recap: Including Files

Summary:

  • require — fatal if missing; for critical files
  • include — warning if missing; for optional files
  • _once variants prevent double-loading
  • Included files share the caller's variable scope
  • Files can return values with return
  • Never include paths from user input — whitelist only

Frequently asked questions

Is the “Including and Requiring Files” lesson free?

Yes — the full text of “Including and Requiring Files” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Including and Requiring Files”?

Split pages into reusable parts with include and require. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Including and Requiring Files” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. PHP Tags and Embedding Syntax
  2. Dynamic HTML with PHP Loops
  3. Including and Requiring Files
  4. Template Pattern: Separating Logic from View
← Back to PHP Academy