PHP include file - The php include function

Home - Tutorials - Basics

In this tutorial I will show you how to divide your code into more files and how to include various files into your actual PHP code.

Tutorial info:

Name:PHP include file
Total steps:5

Bookmark PHP include file

Step 2 - The php include function

PHP include file

The first way to include a file is using the include function. This is a PHP built in code and the synatx is the following:

include ( filename )

This code tries to include the content of the file defined by filename. If the file doesn't exists the include function will report a warning but the script will continue.

Let's see an example. First we create a file which will be included later and it only contains a variable initialisation:

Code: internal.php
  1. <?php
  2. $i = 100;
  3. ?>
After this we create an other file which is the main file and it will include the internal.php as follows:
Code: test.php
  1. <?php
  2. echo "Value of i before include is: -$i-<br/>";
  3. include("internal.php");
  4. echo "Value of i after include is: -$i-<br/>";
  5. ?>
If you run the test.php script you will get an output similar to this:
Value of i before include is: --
Value of i after include is: -100-  
As you can see the variable $i was initialised in the internal.php file and so the first echo couldn't display it. However after we included the file it become part of our code so the second echo function displays it correctly.
Without the include function the code would be something like this:
  1. <?php
  2. echo "Value of i before include is: -$i-<br/>";
  3. $i=100;
  4. echo "Value of i after include is: -$i-<br/>";
  5. ?>
Of course in a real life application your files contains a bit more code :)

Previous Step of PHP include fileNext Step of PHP include file

Tags: php incluude file, php include, include file, file include, php, include, file

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1425