Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP require Statement
The require statement in PHP includes and executes a specified file. Unlike the include statement, if the required file is not found, PHP produces a fatal error and terminates the script execution.
Syntax
require "filename.php";
// or
require("filename.php");
How require Works
PHP searches for the file in the current directory first, then in directories specified in the include_path setting of php.ini. If the file is not found, PHP emits an E_COMPILE_ERROR and halts execution.
Example
Here's a simple example showing how require includes a file ?
<?php echo "Main script started<br>"; $mainVar = 100; // This would normally require an external file // For demo purposes, we'll simulate the behavior echo "Simulating require 'external.php'<br>"; // Code that would be in external.php: $externalVar = 200; echo "Sum: " . ($mainVar + $externalVar) . "<br>"; echo "Main script continues<br>"; ?>
Main script started Simulating require 'external.php' Sum: 300 Main script continues
Error Handling
When a required file is not found, PHP generates a fatal error ?
<?php echo "Script started<br>"; require "nonexistent.php"; // This file doesn't exist echo "This line won't execute<br>"; ?>
This produces a fatal error:
Script started PHP Fatal error: require(): Failed opening required 'nonexistent.php'
require vs include Comparison
| Aspect | require | include |
|---|---|---|
| File not found | Fatal error + script stops | Warning + script continues |
| Use case | Critical files (configs, functions) | Optional files (templates) |
Conclusion
Use require for essential files that your script cannot function without. The fatal error behavior ensures your application doesn't run with missing dependencies.
