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
<?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
<?php
require_once __DIR__ . "/functions.php";
echo h("<b>Tom & Jerry</b>") . "\n";
echo money(1499.5);
<b>Tom & Jerry</b>
Rs. 1,499.50
Now a bug fix or a change happens in one place.
A simple project layout
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:
<?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.
<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/functions.php";
require_once __DIR__ . "/database.php"; // uses config values
Why this matters in WordPress
functions.php first and then pulls other files in with require_once get_template_directory() . "/inc/something.php". It is the same idea.