PHP Include

Su Subhalakshmi Chandran Updated 05 Nov 2026
6 min read ·Lesson 241 of 248

What Does include Do?

In simple terms: include inserts the contents of another PHP file at the point where it is written and runs it there. This lets you write shared parts of a website — a header, a footer, a navigation menu, configuration, or helper functions — once, and reuse them on every page.

Technically: include is a language construct that reads, compiles, and executes the specified file at runtime. The included code runs in the same variable scope as the line that includes it. If the file cannot be found, include emits a warning and returns false, and the script continues.

Why It Is Needed

Without include, every page of a website would repeat the same header, menu, and footer. Changing the menu would mean editing every page. With include:

pages/home.php     ┐
pages/courses.php  ├── include partials/header.php
pages/contact.php  ┘    include partials/footer.php

One change to header.php updates every page.


Syntax

include 'path/to/file.php';
include __DIR__ . '/partials/header.php';

include is a language construct, not a function, so parentheses are not needed (though include('file.php') also works).


partials/header.php

<header><h1><?= htmlspecialchars($pageTitle) ?></h1></header>
<footer>© <?= $year ?> GoCourse</footer>

index.php

<?php
$pageTitle = 'PHP Tutorials';
$year = 2026;

include __DIR__ . '/partials/header.php';

echo "<main>Welcome to the PHP course.</main>\n";

include __DIR__ . '/partials/footer.php';

Output (HTML)

<header><h1>PHP Tutorials</h1></header>
<main>Welcome to the PHP course.</main>
<footer>© 2026 GoCourse</footer>

How It Works

  1. When PHP reaches the first include, it loads header.php and runs it as if its contents were written at that point.
  2. The header uses $pageTitle, which was defined in index.php. Included code shares the variable scope of the including line.
  3. After the included file finishes, execution continues in index.php.
  4. Included files start in HTML mode: text outside <?php ... ?> is output directly, which is why partials can be plain HTML with a few PHP tags.

Using __DIR__ for Reliable Paths

A relative path such as include 'partials/header.php'; is resolved using PHP's include_path setting and the current working directory, which depends on how the script was started — not on where the including file is located. This causes "file not found" errors when the same file is included from different folders or run from the command line.

<?php
// Fragile: depends on the working directory
include 'partials/header.php';

// Reliable: relative to the directory of THIS file
include __DIR__ . '/partials/header.php';
include __DIR__ . '/../config/app.php';   // one folder up

__DIR__ is a magic constant containing the absolute path of the directory of the current file (see PHP Magic Constants). Building paths from it always points to the right file.


Including Configuration: Files That Return Values

An included file can return a value, which becomes the result of the include expression. This is the standard way to write configuration files:

config/app.php

<?php
return [
    'app_name' => 'GoCourse',
    'debug' => false,
    'per_page' => 20,
];

index.php

<?php
$config = include __DIR__ . '/config/app.php';

echo $config['app_name'] . "\n";
var_dump($config['per_page']);

Output

GoCourse
int(20)

Why This Pattern Is Useful

  • The configuration file defines no variables of its own, so it cannot accidentally overwrite variables in the including script.
  • The caller chooses the variable name ($config).
  • Frameworks such as Laravel use exactly this format for their configuration files.

If an included file has no return statement, include returns 1 on success.


Including Function and Class Files

Files that only define functions (or classes) are included once at the start of the application:

src/helpers.php

<?php
function formatPrice(float $amount): string
{
    return '₹' . number_format($amount, 2);
}

index.php

<?php
include_once __DIR__ . '/src/helpers.php';
include_once __DIR__ . '/src/helpers.php';   // ignored: already included

echo formatPrice(1499.5) . "\n";

Output

₹1,499.50

include_once includes a file only if it has not been included before in the current request. Including a file of function definitions twice with plain include would cause a fatal "Cannot redeclare function" error. The differences between include, require, and their _once variants are covered in Include vs Require.

In modern projects, classes are loaded automatically by Composer's autoloader (see Autoloading), so manual includes are mainly used for templates, configuration, and a few helper files.


Variable Scope Inside Functions

Included code takes the scope of the place where include is written. Inside a function, it can see only that function's local variables. This allows a simple and useful template-rendering function:

<?php
// templates/product-card.php
?>
<div class="card">
    <h2><?= htmlspecialchars($name) ?></h2>
    <p>₹<?= number_format($price) ?></p>
</div>
<?php
function render(string $template, array $data): string
{
    extract($data, EXTR_SKIP);

    ob_start();
    include $template;

    return ob_get_clean();
}

$html = render(__DIR__ . '/templates/product-card.php', ['name' => 'Desk Lamp', 'price' => 1299]);

echo $html;

Output (HTML)

<div class="card">
    <h2>Desk Lamp</h2>
    <p>₹1,299</p>
</div>

How It Works

  1. extract($data, EXTR_SKIP) creates local variables ($name, $price) from the array keys, without overwriting existing local variables such as $template.
  2. ob_start() starts output buffering: everything the template outputs is captured instead of being sent to the browser.
  3. include runs the template inside the function, so it sees only the provided data — not the caller's variables.
  4. ob_get_clean() returns the captured HTML and stops buffering.

The result is a string that can be printed, cached, or inserted into a larger layout. Template engines such as Twig and Blade are more advanced versions of the same idea. (Use extract() only with data from your own code, never with request data.)


When the File Is Missing

<?php
$result = include __DIR__ . '/missing.php';

var_dump($result);
echo "The script continues.\n";

Output

PHP Warning:  include(/path/missing.php): Failed to open stream: No such file or directory in /path/index.php on line 2
PHP Warning:  include(): Failed opening '/path/missing.php' for inclusion (include_path='.:/usr/share/php') in /path/index.php on line 2
bool(false)
The script continues.

include produces warnings, returns false, and lets the script continue. That is appropriate for optional parts (for example, an optional local configuration file). For files the application cannot work without, use require instead — see Include vs Require.


Security: Never Include User-Controlled Paths

A common beginner pattern is to choose the page from the URL:

// DANGEROUS
include $_GET['page'] . '.php';

An attacker can request ?page=../../config/secrets and make PHP execute or reveal files outside the intended folder (Local File Inclusion). On misconfigured servers, it might even load code from another website.

Safe Alternative: An Allow-List

<?php
$pages = [
    'home' => __DIR__ . '/pages/home.php',
    'courses' => __DIR__ . '/pages/courses.php',
    'contact' => __DIR__ . '/pages/contact.php',
];

$page = $_GET['page'] ?? 'home';

if (!is_string($page) || !isset($pages[$page])) {
    http_response_code(404);
    $page = 'home';
}

include $pages[$page];

The URL parameter is used only as a key. Only files listed in the array can ever be included. Also keep the PHP setting allow_url_include disabled (the default), so remote URLs can never be included.


Common Mistakes

Relative Paths

Effect: Includes fail depending on where the script is run from.

Fix: Build paths with __DIR__.

Including Function Files More Than Once

Effect: "Cannot redeclare function" fatal errors.

Fix: Use include_once/require_once, or Composer autoloading for classes.

Using include for Essential Files

Effect: The application continues with missing configuration or functions and fails later with confusing errors.

Fix: Use require for required files.

Including Files Based on User Input

Effect: File inclusion vulnerabilities.

Fix: Map input to an allow-list of files.

Unexpected Variable Sharing

Effect: Included files overwrite variables of the including script.

Fix: Return values from configuration files, and render templates inside a function.


Best Practices

  • Use include/require for templates, configuration, and bootstrap files; use Composer autoloading for classes.
  • Always build paths with __DIR__.
  • Use files that return arrays for configuration.
  • Render templates through a function with output buffering to isolate their variables.
  • Never pass user input directly to include.

Official reference: https://www.php.net/manual/en/function.include.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about PHP Include and get answers drawn from it.

Signed-in readers only.