Share via:

PHP: Include, Require, and Include once

Tutorial on how to use PHPs include, include_once and require.


Edited: 2018-01-14 03:41

PHP article image

PHP Includes are useful when writing, simple, reusable, and maintainable code. As a general rule, you should aim to repeat yourself as little as possible, this rule is also known as the Don't Repeat Yoursel (DRY) rule, and includes are just one tool to help you avoid repeating code.

There are a number of different ways to include files in your scripts. In PHP, we have the following: Include, include_once, and require. Each have its own use, which will be explained in this tutorial, and it will be up to you to choose which one fits in your circumstances.

Include and Include_once

Include will attempt to include whatever file specified, regardless if it exist or not. If the file wasn't found, the script will continue running anyway.

include "whatever.php"; // Includes whatever.php

The include_once statement will only include the file, if it has not

include_once "whatever.php"; // Includes whatever.php
include_once "whatever.php"; // Won't do anything, since the file was already included.

If a file was not found, a warning is created. You will only be able to see this warning if you have enabled error reporting for your script.

Warning: include(settings.php): failed to open stream: No such file or directory in path on line 50 Warning: include(): Failed opening 'settings.php' for inclusion (include_path='.;path') in path on line 50

Require, and require_once

Require indicates that the file is required, and that the script should stop executing if the file was not found.

require "whatever.php"; // Includes whatever.php
// The rest of the script, will only be finished if the above require succeeds

A warning will be issued, depending on your error settings. If the warning does not show up in the browser, you can usually find it in the server log files.

Again, Require_once makes sure that the file will only be included once in your application.

Determining the inclusion path

A problem that many programmers run into, is that the path can be difficult to work out. After all, how often are you including files?

In Linux systems, the path is usually absolute. A way to easily determine the path, without having to write the entire path for your web-servers directory, is to use $_SERVER["DOCUMENT_ROOT"]:

require $_SERVER["DOCUMENT_ROOT"] .'lib/db_client_class.php';

Note. In some cases, this variable may have a slash at the end, but this should rarely cause any problems, as double slashes "//" in paths are ignored in Linux.

The above would correspond to the following path in Ubuntu, running the Apache HTTP Server: