PHP Fundamentals

Include & Require

13 min Lesson 8 of 45

Include & Require in PHP

PHP provides file inclusion mechanisms that allow you to insert the content of one PHP file into another. This is essential for code reusability, modular design, and maintaining DRY (Don't Repeat Yourself) principles.

The include Statement

The include statement includes and evaluates the specified file:

<?php // Include a file: include 'header.php'; echo "<h1>Main Content</h1>"; include 'footer.php'; ?>
Note: If the file cannot be found, include produces a warning (E_WARNING) but the script continues execution.

The require Statement

The require statement is identical to include except that it produces a fatal error if the file is not found:

<?php // Require a critical file: require 'config.php'; require 'database.php'; // If config.php doesn't exist, script stops here echo "This won't run if require fails"; ?>
Warning: Use require for critical files (like configuration or database connections) that are essential for your application to run. Use include for optional files (like templates or optional modules).

The include_once and require_once Statements

These variants ensure that a file is included only once, even if called multiple times:

<?php // Include file only once: include_once 'functions.php'; include_once 'functions.php'; // This won't include again // Require file only once: require_once 'config.php'; require_once 'config.php'; // This won't require again ?>
Tip: Use _once variants when including files that define functions, classes, or constants to avoid "already defined" errors.

Comparison Table

Statement On Failure Multiple Includes Use Case
include Warning (script continues) Allowed Optional templates, views
require Fatal Error (script stops) Allowed Critical files, core libraries
include_once Warning (script continues) Once only Optional functions, helpers
require_once Fatal Error (script stops) Once only Classes, configs, functions

File Paths

You can use absolute, relative, or dynamic paths when including files:

<?php // Relative path (from current directory): include 'header.php'; include './header.php'; // Same as above include '../shared/functions.php'; // Parent directory // Absolute path: include '/var/www/html/includes/config.php'; // Using __DIR__ constant (recommended): include __DIR__ . '/includes/config.php'; // Using variables: $template = 'default'; include "templates/{$template}/header.php"; ?>
Tip: Use __DIR__ for reliable path resolution. It returns the directory of the current file, making your includes work regardless of where the script is called from.

Practical Examples

Example 1: Creating a Header File

File: includes/header.php

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $pageTitle ?? 'My Website'; ?></title> <link rel="stylesheet" href="style.css"> </head> <body> <header> <nav> <a href="index.php">Home</a> <a href="about.php">About</a> <a href="contact.php">Contact</a> </nav> </header> <main>

File: includes/footer.php

</main> <footer> <p>&copy; <?php echo date('Y'); ?> My Website</p> </footer> </body> </html>

File: index.php

<?php $pageTitle = "Home Page"; include 'includes/header.php'; ?> <h1>Welcome to My Website</h1> <p>This is the main content.</p> <?php include 'includes/footer.php'; ?>

Example 2: Configuration File

File: config.php

<?php // Database configuration: define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'password'); define('DB_NAME', 'myapp'); // Application settings: define('APP_NAME', 'My Application'); define('APP_URL', 'https://example.com'); define('DEBUG_MODE', true); // Timezone: date_default_timezone_set('UTC'); ?>

File: index.php

<?php require_once 'config.php'; echo "Welcome to " . APP_NAME; if (DEBUG_MODE) { error_reporting(E_ALL); ini_set('display_errors', 1); } ?>

Example 3: Functions Library

File: functions.php

<?php function sanitize($data) { return htmlspecialchars(strip_tags(trim($data))); } function redirect($url) { header("Location: $url"); exit; } function formatDate($date) { return date('F j, Y', strtotime($date)); } function isLoggedIn() { return isset($_SESSION['user_id']); } ?>

Using the functions:

<?php require_once 'functions.php'; $userInput = $_POST['name'] ?? ''; $cleanInput = sanitize($userInput); if (!isLoggedIn()) { redirect('login.php'); } ?>

Variable Scope in Included Files

Variables defined in an included file are available in the including scope:

<?php // File: vars.php $greeting = "Hello"; $name = "John"; // File: main.php include 'vars.php'; echo "$greeting, $name"; // Output: Hello, John // Variables from main.php are also available in included files: $color = "blue"; include 'display.php'; // Can access $color ?>

Return Values from Included Files

Included files can return values using the return statement:

<?php // File: config.php return [ 'database' => [ 'host' => 'localhost', 'user' => 'root', 'pass' => 'password' ], 'app' => [ 'name' => 'My App', 'version' => '1.0.0' ] ]; // File: index.php $config = include 'config.php'; echo $config['app']['name']; // Output: My App ?>
Tip: Returning arrays from config files is a common pattern in modern PHP frameworks. It keeps configuration clean and prevents global namespace pollution.

Conditional Includes

You can conditionally include files based on logic:

<?php $userRole = 'admin'; // Include different files based on conditions: if ($userRole === 'admin') { include 'admin-panel.php'; } else { include 'user-dashboard.php'; } // Include based on existence: if (file_exists('custom-theme.php')) { include 'custom-theme.php'; } else { include 'default-theme.php'; } ?>

Common Patterns and Best Practices

1. Directory Structure Pattern

project/ ├── includes/ │ ├── config.php │ ├── functions.php │ └── database.php ├── templates/ │ ├── header.php │ └── footer.php └── index.php

2. Bootstrap Pattern

<?php // File: bootstrap.php - Load all essential files: require_once __DIR__ . '/config.php'; require_once __DIR__ . '/functions.php'; require_once __DIR__ . '/database.php'; session_start(); // File: index.php require_once 'bootstrap.php'; // All essentials are now loaded ?>

3. Template Pattern

<?php function render($template, $data = []) { extract($data); // Convert array keys to variables include __DIR__ . "/templates/{$template}.php"; } // Usage: render('header', ['title' => 'Home Page']); render('product', ['name' => 'Laptop', 'price' => 999]); render('footer'); ?>

Security Considerations

Security Warning: Never include files based on user input without validation. This can lead to serious security vulnerabilities!
<?php // DANGEROUS - Never do this: $page = $_GET['page']; include $page . '.php'; // User could include any file! // SAFE - Use whitelist validation: $page = $_GET['page'] ?? 'home'; $allowedPages = ['home', 'about', 'contact']; if (in_array($page, $allowedPages)) { include "pages/{$page}.php"; } else { include 'pages/404.php'; } ?>

Performance Considerations

<?php // Use require_once for frequently included files with functions/classes: require_once 'functions.php'; // Plain include is faster if you're sure the file isn't included yet: include 'template.php'; // For large applications, consider using autoloading instead: spl_autoload_register(function ($class) { include "classes/{$class}.php"; }); ?>

Practice Exercise

Task: Create a simple blog system:

  1. Create a config.php file with site name and timezone settings
  2. Create a functions.php file with a function to sanitize text and format dates
  3. Create header.php and footer.php templates
  4. Create an index.php that includes all files and displays a blog post
  5. Bonus: Create a function renderPost($title, $content, $date) that displays a formatted blog post
  6. Extra: Implement a page routing system that safely includes different pages based on URL parameters

Best Practices

  • Use require or require_once for critical files
  • Use include or include_once for optional files
  • Always use _once variants for files with functions, classes, or constants
  • Use __DIR__ for reliable path resolution
  • Keep included files in organized directories (includes/, templates/, config/)
  • Never include files based on unvalidated user input
  • Use a whitelist approach when including user-selected files
  • Consider using autoloading for class files in larger applications
  • Return arrays from config files instead of defining global constants
  • Check file existence before including optional files

ES
Edrees Salih
15 hours ago

We are still cooking the magic in the way!