PHP Include, Require and Include once Tutorial

Tutorial on Included files in PHP. How to include files in PHP Scripts, and avoid common errors.

PHP includes, also known as server-side includes, is a useful way to help maintain, and to minimize your scripts.

In this Tutorial, we will cover three types of includes. The normal PHP Include, the include_once, and the require include statements. Each have their own use, which will be explained in this Tutorial, it will be up to you to chose which you want to use in your own scripts.

Include and Include_once

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

<?php
include "whatever.php"; // Includes whatever.php
?>

The PHP include_once statement will only include the file if it hasn't been included earlier in the script.

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

If a file wasn't 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

The PHP Require

The PHP Require might be what you are looking for, after all, normally you don't want the rest of your script to run if one of your includes fail, as this could lead to disastrous errors.

The require statement tells PHP to stop if the file couldn't be included. In other words, if the file was not found, the rest of the script will simply not be completed, and a warning is outputted if you have errors turned on.

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

Post comment

Links that you insert are not nofollowed, but will be removed by admins if they are considered spam.

[url=Absolute URL for page]TITLE[/url]

You should insert code boxes around code examples, which will be automatically syntax highlighted.

[code1 html|css|javascript|php|sql]Your Code Here[/code1]

You may want to read our Privacy Policy before submitting your comment.