PHP Include
Reusing code across multiple pages
📂 What is PHP Include?
PHP include allows you to insert reusable code from one file into another. This helps maintain consistent headers, footers, and navigation across your website without duplicating code.
<?php
// Include a file
include 'header.php';
?>
Include Methods
include
Insert file, continue on error
<?php
include 'file.php';
?>
require
Insert file, stop on error
<?php
require 'file.php';
?>
include_once
Include file only once
<?php
include_once 'file.php';
?>
require_once
Require file only once
<?php
require_once 'file.php';
?>
🔹 Basic Include Example
Include a header file in your main page:
🔸 header.php
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
header {
background: #333;
color: white;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<a href="index.php">Home</a> |
<a href="about.php">About</a> |
<a href="contact.php">Contact</a>
</nav>
</header>
🔸 index.php
<?php include 'header.php'; ?>
<main>
<h2>Home Page</h2>
<p>This is the main content of the home page.</p>
</main>
<?php include 'footer.php'; ?>
🔸 footer.php
<footer style="background: #333; color: white; padding: 20px; text-align: center; margin-top: 20px;">
<p>© 2025 My Website. All rights reserved.</p>
</footer>
</body>
</html>
🔹 Include vs Require
Understanding the difference between include and require:
<?php
// include - Shows warning if file not found, continues execution
include 'optional_file.php';
echo "This will still execute even if file is missing<br>";
// require - Shows fatal error if file not found, stops execution
require 'critical_file.php';
echo "This won't execute if file is missing<br>";
?>
When to use each:
- include: For optional files like templates or non-critical components
- require: For essential files like database connections or configuration
- include_once: For files that should only be loaded once (prevents redeclaration)
- require_once: For critical files that must be loaded exactly once (like classes)
🔹 Include with Variables
Pass and use variables between included files:
🔸 config.php
<?php
// Configuration variables
$siteName = "My Awesome Website";
$siteEmail = "[email protected]";
$siteYear = 2025;
?>
🔸 page.php
<?php
// Include configuration
include 'config.php';
// Use variables from included file
echo "<h1>$siteName</h1>";
echo "<p>Contact us: $siteEmail</p>";
echo "<p>© $siteYear</p>";
?>
🔹 Include with Functions
Create reusable functions in separate files:
🔸 functions.php
<?php
// Reusable functions
function greet($name) {
return "Hello, " . htmlspecialchars($name) . "!";
}
function formatDate($date) {
return date("F j, Y", strtotime($date));
}
function calculateAge($birthdate) {
$diff = date_diff(date_create($birthdate), date_create('today'));
return $diff->y;
}
?>
🔸 main.php
<?php
require_once 'functions.php';
// Use functions from included file
echo greet("John") . "<br>";
// Output: Hello, John!
echo "Today is " . formatDate("2025-10-02") . "<br>";
// Output: Today is October 2, 2025
echo "Age: " . calculateAge("1990-05-15") . " years old<br>";
// Output: Age: 35 years old
?>
🔹 Dynamic Navigation Menu
Create a reusable navigation menu with active page highlighting:
🔸 navigation.php
<?php
$currentPage = basename($_SERVER['PHP_SELF']);
$menuItems = [
'index.php' => 'Home',
'about.php' => 'About',
'services.php' => 'Services',
'contact.php' => 'Contact'
];
?>
<nav style="background: #333; padding: 10px;">
<?php foreach ($menuItems as $page => $title): ?>
<a href="<?php echo $page; ?>"
style="color: <?php echo ($currentPage == $page) ? '#ff0' : '#fff'; ?>;
padding: 10px;
text-decoration: none;">
<?php echo $title; ?>
</a>
<?php endforeach; ?>
</nav>
🔸 Any page
<?php include 'navigation.php'; ?>
<h1>Page Content</h1>
<p>The navigation menu will highlight the current page automatically.</p>
🔹 Database Connection Include
Centralize database connection in a separate file:
🔸 db_connect.php
<?php
// Database configuration
$host = 'localhost';
$dbname = 'mywebsite';
$username = 'root';
$password = '';
try {
// Create PDO connection
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Connection successful
} catch(PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
🔸 users.php
<?php
require_once 'db_connect.php';
// Use the database connection
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($users as $user) {
echo $user['name'] . "<br>";
}
?>
🔹 Template System
Build a simple template system using includes:
🔸 template.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $pageTitle ?? 'My Website'; ?></title>
<style>
body { font-family: Arial, sans-serif; margin: 0; }
header { background: #333; color: white; padding: 20px; }
main { padding: 20px; min-height: 400px; }
footer { background: #333; color: white; padding: 20px; text-align: center; }
</style>
</head>
<body>
<header>
<h1><?php echo $pageTitle ?? 'My Website'; ?></h1>
<?php include 'navigation.php'; ?>
</header>
<main>
<?php echo $content ?? ''; ?>
</main>
<footer>
<p>© 2025 My Website</p>
</footer>
</body>
</html>
🔸 about.php
<?php
$pageTitle = "About Us";
$content = "
<h2>About Our Company</h2>
<p>We are a leading company in our industry...</p>
<p>Founded in 2020, we have grown to serve thousands of customers.</p>
";
include 'template.php';
?>
🔹 Include Path Best Practices
Handle file paths correctly for includes:
<?php
// Relative path (from current file location)
include 'header.php';
include '../includes/header.php';
include './components/menu.php';
// Absolute path (from server root)
include $_SERVER['DOCUMENT_ROOT'] . '/includes/header.php';
// Using constants for paths
define('ROOT_PATH', dirname(__FILE__));
include ROOT_PATH . '/includes/header.php';
// Check if file exists before including
$file = 'config.php';
if (file_exists($file)) {
include $file;
} else {
die("Configuration file not found!");
}
// Include with error handling
if (!@include 'optional.php') {
echo "Optional file not loaded, using defaults.";
}
?>
🔹 Common Include Patterns
Typical file structure for PHP projects:
Project Structure:
/mywebsite
/includes
header.php
footer.php
navigation.php
db_connect.php
/functions
helpers.php
validation.php
/config
config.php
constants.php
index.php
about.php
contact.php
<?php
// Typical page structure
require_once 'config/config.php';
require_once 'includes/db_connect.php';
require_once 'functions/helpers.php';
include 'includes/header.php';
?>
<!-- Page content here -->
<h1>Welcome</h1>
<p>Page content...</p>
<?php include 'includes/footer.php'; ?>