Skip to content

PHP Tutorial Include and Require

Reusing PHP Files

Lesson 158 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Imagine a site with ten pages. Each needs the same helper to escape output. If you copy the helper into every page, fixing a bug means editing ten files.

Put it in one file, and load that file everywhere.

Step 1: a shared functions file

functions.php
PHP
<?php
declare(strict_types=1);

function h(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES, "UTF-8");
}

function money(float $amount): string
{
    return "Rs. " . number_format($amount, 2);
}

Step 2: use it from any page

index.php
PHP
<?php
require_once __DIR__ . "/functions.php";

echo h("<b>Tom & Jerry</b>") . "\n";
echo money(1499.5);
Output
OUTPUT
&lt;b&gt;Tom &amp; Jerry&lt;/b&gt;
Rs. 1,499.50

Now a bug fix or a change happens in one place.

A simple project layout

Text
PLAIN
my-site/
├── public/            <- the only folder the web server exposes
│   ├── index.php
│   └── contact.php
├── includes/
│   ├── functions.php
│   └── config.php
└── templates/
    ├── header.php
    └── footer.php

Each public page starts with:

index.php
PHP
<?php
require_once __DIR__ . "/../includes/functions.php";

Files outside public/ cannot be opened directly from a browser. That protects your configuration files and code.

What belongs in a shared file

  • Helper functions (escaping, formatting, redirects).
  • Configuration.
  • Class definitions (until you use an autoloader).
  • Page parts (header, footer, navigation).

What does not belong

  • Code that runs a page-specific action. Keep that in the page itself.
  • Secrets in a file inside the web folder.

Include order matters

A file must be loaded before you use what it defines. Load configuration first, then functions, then anything that depends on them.

index.php
PHP
<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/functions.php";
require_once __DIR__ . "/database.php";   // uses config values
info
Why this matters in WordPress
A WordPress theme loads functions.php first and then pulls other files in with require_once get_template_directory() . "/inc/something.php". It is the same idea.