<< PHP Do While Loop | PHP Tutorials | PHP/HTML Forms >>

PHP Include and Require

A PHP include will include any file you have on your site in the script you are including it from. For example if you wanted to have the same header on each page, you would put that header information into a file and then on each page use a PHP include to include the header. If the include is a PHP script, the script will be run as if the information was actually inside the script. This means that all variables inside an included file can be used in the script you are including from, if it is after the file is included. This also means that any variables inside your script that you are including from can pass variables to the script if they are declared before the include is... included, jeez that was a mouthful :)

include and include_once

There are 4 main ways to include files in PHP. The two I'm going to talk about now are include() and include_once(). These are not real functions in PHP, they are language constructs therefore they don't need the parentheses (brackets). In this tutorial I will be using brackets.

There is a difference between these two. The include() language construct will allow you to include the same file multiple times. The include_once() language construct will only allow you to include the file once throughout the whole script. Here are several examples of both:

<?php
$file = 'file.php';
$yet_another_file = 'yet_another_file.php';
include('file.php');
include 'file.php';
include $file;

include_once('file.php');
include_once 'another_file.php';
include_once $yet_another_file;
?>

You need 4 different files to make this example work because the include_once() will only let you include once! :) Now let's say I had this file:

<?php
$variable = 'Hello';
?>

And it was called 'file.php'. You could include this file and then print out the variable that is set in it:

<?php
include('file.php');
echo $variable;
?>

This is what the end users will see:

Hello

require and require_once

There isn't a significant difference between require and include. The only difference is that the require() and require_once() will output a Fatal Error if the file is not found. They can be used in a script the exact same way the include() and include_once() but still here is an example for ya:

<?php
$file = 'file.php';
$yet_another_file = 'yet_another_file.php';
require('file.php');
require 'file.php';
require $file;

require_once('file.php');
require_once 'another_file.php';
require_once $yet_another_file;
?>

<< PHP Do While Loop | PHP Tutorials | PHP/HTML Forms >>