Introduction
In PHP, the include and require statements are used to insert the contents of one PHP file into another PHP file. These statements help developers reuse code, organize projects, and simplify website management.
Using include and require is very useful when working with headers, footers, navigation menus, database connections, and reusable functions.
Objectives
By the end of this training, you will be able to:
- Understand include and require statements
- Reuse code across multiple pages
- Reduce duplicate code in projects
- Organize PHP applications efficiently
- Handle errors related to file inclusion
What is Include in PHP
The include statement inserts a file into another PHP file during execution.
If the file is missing, PHP shows a warning but the script continues running.
Syntax
include 'filename.php';
Example
Create a file named header.php
<?php
echo "<h1>Welcome to My Website</h1>";
?>
Main file:
<?php
include 'header.php';
echo "This is the homepage.";
?>
Output
Welcome to My Website
This is the homepage.
What is Require in PHP
The require statement also inserts a file into another PHP file.
If the file is missing, PHP shows a fatal error and stops the script execution.
Syntax
require 'filename.php';
Example
<?php
require 'header.php';
echo "This is the homepage.";
?>
Difference Between Include and Require
Include
- Shows a warning if file is missing
- Script continues running
- Used for optional files
Require
- Shows a fatal error if file is missing
- Script stops immediately
- Used for important files
Include Once and Require Once
PHP also provides include_once and require_once to prevent loading the same file multiple times.
include_once Example
<?php
include_once 'menu.php';
?>
require_once Example
<?php
require_once 'config.php';
?>
Why Use Include and Require
Code Reusability
Write code once and use it on multiple pages.
Easy Maintenance
Update one file and changes appear everywhere.
Better Project Structure
Separate headers, footers, and functions into different files.
Faster Development
Save time by avoiding repeated code.
Common Use Cases
Header and Footer Files
<?php
include 'header.php';
include 'footer.php';
?>
Database Connection
<?php
require 'db_connection.php';
?>
Navigation Menu
<?php
include 'menu.php';
?>
Best Practices
- Use require for critical files
- Use include for optional sections
- Use require_once for configuration files
- Keep reusable files organized in folders
- Use meaningful file names
Advantages of Include and Require
- Reduces duplicate code
- Improves code organization
- Makes websites easier to maintain
- Saves development time
- Supports modular programming
Final Presentation
In your final presentation, explain:
- What include and require are
- Differences between include and require
- How reusable files improve website development
- Examples of include and require statements
- Benefits of modular PHP coding