PHP 5 Include Function
How to use PHP include function
The include () function enables you to embed PHP script into another PHP scripts. It's used for embedding library code in multiple pages.
Syntax of include function
include (< path >);
There are two file abp.php and xyz.php, that have some code means both file print something.
abp.php
<?php echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
"; echo "First file content
"; echo "Working with include function
"; echo "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
"; ?>
- Example
- Run
xyz.php
<?php echo "********************************
"; echo "Second file content
"; echo "Working with include function
"; echo "********************************
"; ?>
- Example
- Run
Now both files are included with fgh.php file as shown in the below example.
fgh.php
<?php include('abp.php'); include('xyz.php'); echo "$$$$$$$$$$$$$$$$$$$$$$$$$$$$
"; echo "thirt file content
"; echo "Working with include function
"; echo "$$$$$$$$$$$$$$$$$$$$$$$$$$$$
"; ?>
- Example
- Run
The file fgh.php has some code but before executing the fgh.php, abp.php and xyz.php will be executed and finally combine result obtain.(abp + xyz+fgh)
Advantage of include function
Basically include function are used for making such section of the site that are fixed for all the pages like menus, share buttons etc.
Another example of include function
<?php include('abp.php'); include('xyz.php'); include('xyz.php'); include('xyz.php'); include('abp.php'); echo "You can include."; echo "file any number of times"; ?>
- Example
- Run
Working with Include Paths
Including path is the more important factor at the time of including any file. Suppose you are working with large project tracing of path to include is very difficult.
Example of path
If You are working in same directory, use below syntax
Include (‘file-name’);
Example of path
Suppose your all common code libraries into /home/ll/reuse/zxa.php folder and you have lisite in /home/ll/doc/name.php/. You want to include a page from modular-code folder to doc foder use following code.
By using absolute path:
include( '/home/ll/reuse/zxa.php' );
By using alternative path
include( '../lib/zxa.php' );
Suppose your all modular code (code modular-code) within subfolder cars. You put your list.php file into car folder. The path of the file are following bellow /home/ll/reuse/car/zxa.php
To include
include( 'car/zxa.php' );