PHP Include
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).
A First Example: Shared Header and Footer
partials/header.php
<header><h1><?= htmlspecialchars($pageTitle) ?></h1></header>
partials/footer.php
<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
- When PHP reaches the first
include, it loadsheader.phpand runs it as if its contents were written at that point. - The header uses
$pageTitle, which was defined inindex.php. Included code shares the variable scope of the including line. - After the included file finishes, execution continues in
index.php. - 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
extract($data, EXTR_SKIP)creates local variables ($name,$price) from the array keys, without overwriting existing local variables such as$template.ob_start()starts output buffering: everything the template outputs is captured instead of being sent to the browser.includeruns the template inside the function, so it sees only the provided data — not the caller's variables.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/requirefor templates, configuration, and bootstrap files; use Composer autoloading for classes. - Always build paths with
__DIR__. - Use files that
returnarrays 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