How to Use include and require in PHP: Syntax and Examples
In PHP,
include and require are used to insert the contents of one PHP file into another. include gives a warning if the file is missing but continues running, while require causes a fatal error and stops the script if the file is missing.Syntax
include and require are followed by the file path in quotes. You can use parentheses or not. Both accept relative or absolute paths.
include 'file.php';- Inserts the file and continues if missing.require 'file.php';- Inserts the file and stops if missing.- Use
_oncevariants to include files only once to avoid duplicates.
php
<?php include 'file.php'; require 'file.php'; include_once 'file.php'; require_once 'file.php'; ?>
Example
This example shows how include and require work by including a file that defines a function and then calling it.
php
<?php // contents of greetings.php // <?php // function sayHello() { // echo "Hello, world!\n"; // } include 'greetings.php'; sayHello(); require 'greetings.php'; sayHello(); ?>
Output
Hello, world!
Hello, world!
Common Pitfalls
Missing file: include only warns and continues, which can cause errors later if the file is essential. require stops the script immediately, which is safer for critical files.
Multiple inclusions: Including the same file multiple times can cause function redefinition errors. Use include_once or require_once to prevent this.
php
<?php // Wrong: including same file twice include 'greetings.php'; include 'greetings.php'; // causes error if functions repeat // Right: include once include_once 'greetings.php'; include_once 'greetings.php'; // no error ?>
Quick Reference
| Function | Behavior on Missing File | Multiple Inclusion Protection |
|---|---|---|
| include | Warning, script continues | No |
| require | Fatal error, script stops | No |
| include_once | Warning, script continues | Yes |
| require_once | Fatal error, script stops | Yes |
Key Takeaways
Use
require for files essential to your script to stop execution if missing.Use
include when the file is optional and you want the script to continue if missing.Prevent errors from multiple inclusions by using
include_once or require_once.Both
include and require accept relative or absolute file paths.Always check file paths carefully to avoid warnings or fatal errors.