PHP Include and Require
# 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
includestatement to insert PHP/HTML files.
-
Use the
requirestatement for critical file inclusion.
-
Understand the difference between
includeandrequire.
-
Understand
includeonceandrequireonce.
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:
Now, inside index.php:
4. The require Statement
The require statement does the exact same thing as include, with one massive difference: Error Handling.
-
If an
includefails (e.g., the file is missing), PHP throws a Warning and continues executing the rest of the script.
-
If a
requirefails, PHP throws a Fatal Error and stops the script completely.
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, useincludeonce or requireonce. PHP will check if the file has already been included; if it has, it will not include it again.
6. Real-World Examples
A standard PHP website architecture separates the layout into components. You will typically have aheader.php, a footer.php, and page-specific files like index.php and about.php.
header.php
*(Notice the <body> and <html> tags are left open!)*
footer.php
*(Here we close the tags opened in the header!)*
7. Putting It Together
Now, to create the homepage (index.php), it is incredibly clean:
8. Output Explanations
When a user visitsindex.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.phpcontains</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 calledincludes, you must writeinclude 'includes/header.php';.
-
Using
includefor critical files: Usingincludefor a database connection file. If it fails, the script continues, likely revealing errors and raw code to the user. Always userequirefor configurations and databases.
10. Best Practices
-
Place all reusable layout files (header, footer, nav, sidebar) into a dedicated folder named
includes/orcomponents/to keep your root directory clean.
-
Use
require_oncefor PHP logic files (like function libraries or database connections) andincludefor HTML layout snippets.
11. Exercises
-
1.
Create a
menu.phpcontaining an HTML unordered list of links.
-
2.
Create two pages,
page1.phpandpage2.php, andincludethe menu into both.
-
3.
Change a link in
menu.phpand 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
contact.php
13. Coding Challenges
Challenge 1: Write a script that attempts torequire 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 betweeninclude 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 withinclude 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 usinginclude, enforce critical dependencies using require, and construct professional, easily maintainable multi-page websites.