Skip to main content
PHP for Beginners
CHAPTER 15 Beginner

PHP Include and Require

Updated: May 12, 2026
15 min read

# Chapter 15: PHP Include and Require

1. Introduction

Welcome to Chapter 15! If you build a website with 20 pages, and every page has the exact same HTML navigation menu and footer, what happens when you want to add a new link to the menu? In standard HTML, you have to manually edit all 20 pages. This is a maintenance nightmare. PHP solves this elegantly using file inclusion. By writing the navigation code once in a separate file, you can "include" it into all 20 pages. If you update that one file, the change instantly reflects across the entire website!

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Modularize website layouts by separating headers, footers, and content.
  • Use the include statement to insert PHP/HTML files.
  • Use the require statement for critical file inclusion.
  • Understand the difference between include and require.
  • Understand includeonce and requireonce.

3. The include Statement

The include statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.

Example Setup: Imagine a file named footer.php:

php
123
<footer>
    <p>Copyright © 2026 My Awesome Website</p>
</footer>

Now, inside index.php:

php
123456789
<!DOCTYPE html>
<html>
<body>
    <h1>Welcome to the Homepage!</h1>
    <p>Here is the main content.</p>
    
    <?php include &#039;footer.php'; ?>
</body>
</html>

4. The require Statement

The require statement does the exact same thing as include, with one massive difference: Error Handling.
  • If an include fails (e.g., the file is missing), PHP throws a Warning and continues executing the rest of the script.
  • If a require fails, PHP throws a Fatal Error and stops the script completely.
php
12345
<?php
// If database.php is missing, the site crashes immediately.
// This is good! We don't want the site running without a database.
require &#039;database_connection.php'; 
?>

5. Includeonce and Requireonce

Sometimes in complex applications, you might accidentally include the same file twice. If that file contains PHP functions, declaring the same function twice will cause a fatal error. To prevent this, use includeonce or requireonce. PHP will check if the file has already been included; if it has, it will not include it again.
php
12345
<?php
require_once &#039;functions.php';
// Even if we type it again, PHP ignores it safely.
require_once &#039;functions.php'; 
?>

6. Real-World Examples

A standard PHP website architecture separates the layout into components. You will typically have a header.php, a footer.php, and page-specific files like index.php and about.php.

header.php

php
1234567891011
<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <style> nav { background: #333; color: white; padding: 10px; } </style>
</head>
<body>
    <nav>
        <a href="index.php" style="color:white;">Home</a> | 
        <a href="about.php" style="color:white;">About</a>
    </nav>

*(Notice the <body> and <html> tags are left open!)*

footer.php

php
123456
    <footer style="margin-top: 50px;">
        <hr>
        <p>End of page.</p>
    </footer>
</body>
</html>

*(Here we close the tags opened in the header!)*

7. Putting It Together

Now, to create the homepage (index.php), it is incredibly clean:
php
12345678
<?php include &#039;header.php'; ?>

<main style="padding: 20px;">
    <h2>Welcome Home</h2>
    <p>This is the unique content for the homepage.</p>
</main>

<?php include &#039;footer.php'; ?>

8. Output Explanations

When a user visits index.php, the PHP engine fetches header.php and outputs the <html>, <head>, and <nav>. It then outputs the <main> content from index.php. Finally, it fetches footer.php and outputs the closing </body> and </html> tags. The browser receives one perfect, unified HTML document.

9. Common Mistakes

  • Closing tags incorrectly: If your header.php contains </html>, the document ends there. Your main content will be placed outside the valid HTML structure, breaking the design.
  • Wrong file paths: include 'header.php'; looks in the *same folder*. If your header is in a folder called includes, you must write include 'includes/header.php';.
  • Using include for critical files: Using include for a database connection file. If it fails, the script continues, likely revealing errors and raw code to the user. Always use require for configurations and databases.

10. Best Practices

  • Place all reusable layout files (header, footer, nav, sidebar) into a dedicated folder named includes/ or components/ to keep your root directory clean.
  • Use require_once for PHP logic files (like function libraries or database connections) and include for HTML layout snippets.

11. Exercises

  1. 1. Create a menu.php containing an HTML unordered list of links.
  1. 2. Create two pages, page1.php and page2.php, and include the menu into both.
  1. 3. Change a link in menu.php and verify it updates on both pages simultaneously.

12. Mini Project: Multi-Page Architecture

Task: Create a dynamic page layout where the page title changes dynamically based on a variable defined before the header is included.

includes/header.php

php
12345678910
<!DOCTYPE html>
<html>
<head>
    <!-- Use the variable defined in the parent file! -->
    <title><?php echo isset($page_title) ? $page_title : "Default Title"; ?></title>
</head>
<body>
    <header style="background: lightblue; padding: 15px;">
        <h1>Company Logo</h1>
    </header>

contact.php

php
123456789101112
<?php 
// Define the variable BEFORE including the header!
$page_title = "Contact Us - My Company"; 
include &#039;includes/header.php'; 
?>

<div class="content">
    <h2>Contact Information</h2>
    <p>Call us at 555-0199.</p>
</div>

<?php include &#039;includes/footer.php'; ?>

13. Coding Challenges

Challenge 1: Write a script that attempts to require a file named doesnotexist.php. Follow it with an echo "This will not print"; statement. Run the script and observe how require strictly halts the execution.

14. MCQs with Answers

1. What is the primary difference between include and require? A) include is for HTML, require is for PHP. B) On failure, include throws a warning and continues, while require throws a fatal error and halts the script. C) require is faster than include. D) include can be used multiple times, require only once. *Answer: B*

2. Which function ensures a file is not accidentally included twice, preventing "function already declared" errors? A) includestrict B) requireonly C) requireonce D) importonce *Answer: C*

3. If you define a variable in index.php and then include 'footer.php', can the footer access that variable? A) No, includes have their own variable scope. B) Yes, the included file inherits the variable scope of the line where the include occurs. C) Only if you pass it as a parameter. D) Only if the variable is an array. *Answer: B*

15. Interview Questions

Q: How does modularizing a website with include improve maintainability? *A:* It adheres to the DRY (Don't Repeat Yourself) principle. By centralizing common UI elements like the navbar and footer into single files, any updates to the design or links only need to be made in one place. The changes instantly propagate to every page that includes those files, saving hours of manual editing and reducing errors.

Q: Explain how variable scope works with included files. *A:* When a file is included, the code it contains inherits the variable scope of the exact line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, and vice versa.

16. FAQs

Q: Is it safe to include files based on URL parameters (e.g., include $_GET['page'] . '.php';)? *A:* NO! This is a massive security vulnerability called Local File Inclusion (LFI). Attackers can manipulate the URL to include sensitive server files (like password configurations). Always strictly validate and whitelist what files are allowed to be included.

17. Summary

You are now an architect! You learned how to tear down monolithic web pages into reusable, modular components. You understand how to inject headers and footers using include, enforce critical dependencies using require, and construct professional, easily maintainable multi-page websites.

18. Next Chapter Recommendation

We can pass variables to included files, but what about passing variables as a user moves from page to page across the whole site (like staying logged in)? In Chapter 16: PHP Sessions and Cookies, we will master the art of tracking users across the stateless web!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·