PHP Program to Demonstrate Files (include vs require)
Learn PHP step by step.
All about PHP - Files (include vs require)
Jan 29, 2026
## Chapter 12: Files (include vs require)
Goal of this chapter: split code into files without “why is this loaded twice?” problems.
- `include` warns if file missing and continues
- `require` is a fatal error if file missing
- `*_once` prevents double-loading
Typical pattern:
```php
<?php
**Splitting code into files is like organizing your kitchen - everything has its place and you can find it easily!**
**Files help you avoid the "where did I put that function?" problem!**
### Include vs Require - Different Ways to Bring in Ingredients
**Think of include/require like different ways to get ingredients for your recipe:**
| Command | What It Does | When to Use |
|---------|---------------|-------------|
| `include` | Shows a warning if file missing, continues cooking | For optional features |
| `require` | Stops everything if file missing | For essential files |
| `include_once` | Same as include, but won't load twice | For functions that might be loaded multiple times |
| `require_once` | Same as require, but won't load twice | For configuration files |
**Visual Example:**
```
┌─────────────────────────────────────────┐
│ Your Main Recipe (index.php) │
├─────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ │
│ │ include 'header.php' │─── Warning if missing │
│ └─────────────────┘ │
│ │
│ ┌─────────────────┐ │
│ │ require 'config.php' │─── Stop if missing! │
│ └─────────────────┘ │
│ │
│ ┌─────────────────┐ │
│ │ require_once 'functions.php' │─── Load only once │
│ └─────────────────┘ │
│ │
└─────────────────────────────────────────┘
```
### Real-World File Organization
**Example: Organizing a website**
```
my-website/
├── index.php # Main page
├── config.php # Database settings, site config
├── functions.php # Helper functions
├── header.php # Top navigation
├── footer.php # Bottom section
└── database/
└── connection.php # Database connection
```
**Your main file (index.php):**
```php
<?php
// Load essential configuration first
require_once __DIR__ . "/config.php";
// Load helper functions
require_once __DIR__ . "/functions.php";
// Include page parts
include __DIR__ . "/header.php";
?>
<main>
<h1>Welcome to My Site</h1>
<p>Content goes here...</p>
</main>
<?php
include __DIR__ . "/footer.php";
?>
```
### Common File Patterns
**Configuration File (config.php):**
```php
<?php
// Database settings
define('DB_HOST', 'localhost');
define('DB_NAME', 'myapp');
define('DB_USER', 'root');
define('DB_PASS', '');
// Site settings
define('SITE_NAME', 'My Awesome Site');
define('SITE_URL', 'http://localhost');
?>
```
**Functions File (functions.php):**
```php
<?php
function connectDatabase(): PDO {
try {
return new PDO(
"mysql:host=" . DB_HOST . ";dbname=" . DB_NAME,
DB_USER,
DB_PASS
);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
function formatDate(string $date): string {
return date("F j, Y", strtotime($date));
}
function sanitizeInput(string $input): string {
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
?>
```
### File Loading Best Practices
**Always use absolute paths with `__DIR__`:**
```php
<?php
// Good - works from any directory
require_once __DIR__ . "/../config.php";
// Bad - might break if you run from different directory
require_once "config.php";
?>
```
**Load files in order of dependency:**
```php
<?php
// 1. Configuration first (defines constants)
require_once __DIR__ . "/config.php";
// 2. Functions next (might use constants)
require_once __DIR__ . "/functions.php";
// 3. Then database connection
require_once __DIR__ . "/database/connection.php";
// 4. Finally, page content
include __DIR__ . "/header.php";
?>
```
### Common Mistakes with Files
| Mistake | What Happens | How to Fix |
|---------|---------------|------------|
| Using relative paths | Breaks when running from different directories | Always use `__DIR__` |
| Loading files twice | Function redefinition errors | Use `*_once` versions |
| Wrong include order | Constants not defined yet | Load dependencies first |
| Forgetting to close PHP tag | Headers already sent error | Don't close `?>` in pure PHP files |
| Using `include` for critical files | Site breaks silently | Use `require` for essential files |
### Practice Exercises
**Exercise 1: Create a Simple Website Structure**
```
my-site/
├── index.php
├── config.php # Site settings
├── functions.php # Helper functions
├── header.php # Top navigation
└── footer.php # Bottom section
```
**Exercise 2: Build a Contact Form**
Create separate files for:
- Configuration (database settings)
- Functions (validation, email sending)
- Form display
- Form processing
**Exercise 3: Debug File Loading Issues**
```php
<?php
// Add this to debug file loading
echo "Loading: " . __FILE__ . "n";
echo "Current dir: " . __DIR__ . "n";
echo "Trying to load: " . __DIR__ . "/config.phpn";
// Check if file exists before loading
if (file_exists(__DIR__ . "/config.php")) {
require_once __DIR__ . "/config.php";
echo "Config loaded successfully!n";
} else {
echo "Config file not found!n";
}
?>
```
```
---
## Conclusion
In this article, we explored the core concepts of All about PHP - Files (include vs require). Understanding these fundamentals is crucial for any developer looking to master this topic.
## Frequently Asked Questions (FAQs)
**Q: What is All about PHP - Files (include vs require)?**
A: All about PHP - Files (include vs require) is a fundamental concept in this programming language/topic that allows developers to perform specific tasks efficiently.
**Q: Why is All about PHP - Files (include vs require) important?**
A: It helps in organizing code, improving performance, and implementing complex logic in a structured way.
**Q: How to get started with All about PHP - Files (include vs require)?**
A: You can start by practicing the basic syntax and examples provided in this tutorial.
**Q: Are there any prerequisites for All about PHP - Files (include vs require)?**
A: Basic knowledge of programming logic and syntax is recommended.
**Q: Can All about PHP - Files (include vs require) be used in real-world projects?**
A: Yes, it is widely used in enterprise-level applications and software development.
**Q: Where can I find more examples of All about PHP - Files (include vs require)?**
A: You can check our blog section for more advanced tutorials and use cases.
**Q: Is All about PHP - Files (include vs require) suitable for beginners?**
A: Yes, our guide is designed to be beginner-friendly with clear explanations.
**Q: How does All about PHP - Files (include vs require) improve code quality?**
A: By providing a standardized way to handle logic, it makes code more readable and maintainable.
**Q: What are common mistakes when using All about PHP - Files (include vs require)?**
A: Common mistakes include incorrect syntax usage and not following best practices, which we've covered here.
**Q: Does this tutorial cover advanced All about PHP - Files (include vs require)?**
A: This article covers the essentials; stay tuned for our advanced series on this topic.