Skip to Content

Include Files in PHP

PHP allows you to include other files with the .php extension using four different statements: include, include_once, require, and require_once.

Each of these four statements does almost the exact same thing, with a few slight differences in functionality. We'll go over each of these statements in this tutorial.

Example

To include a PHP file, use either of the four statements with the following syntax:

include "file.php";
include_once "file.php";
require "file.php";
require_once "file.php";

Although not required, you could alter the syntax by wrapping parenthesis around your file names:

include("file.php");
include_once("file.php");
require("file.php");
require_once("file.php");

Include

The include statement simply loads the contents of another PHP file. If the file does not exist, a warning message will display on the screen, but the remainder of the script will process regularly.

Include Once

The include_once statement works the same as include except it checks if the same script is loaded multiple times. If the same script is loaded again after its initial load, it will ignore subsequent includes of the same script.

Require

The require statement works similarly to include in that it loads a specific PHP script that you pass it. The difference is that the script will throw an error and stop processing immediately if the included PHP script file does not exist.

Require Once

The require_once statement will stop processing the PHP script if the file doesn't exist on the server, but it will also only include and process a PHP file once if it's included multiple times throughout your script.

Include Path Examples

There are several ways you can include PHP files. You can use relative paths, where the script included is in the same directory as the running script:

include "file.php";

You can include scripts within a subdirectory:

include "folder/file.php";

You can also include scripts using absolute paths:

include "/var/www/app/folder/file.php";

Conclusion

This tutorial covered four ways of including other PHP files throughout your script, each with use cases and examples.

Created: August 28, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.