How to use PHP Include by including file path in main PHP file

Introduction to include function

This is very common practice of simplifying code as much as a coder can. One of the methods offered by programing languages, including PHP is to separate certain part of code into other files, that can be .php or .html etc. The two benefits of using this approach are:

Code is simplified

Writing all your code in one PHP page may make it harder for future use, after years.

Reusing code

You can develop one part of your web site into one page of php file and reuse this into many pages. For example Headers, Footer, Left/Right navigation are generally common to whole site. Now think how handy it is if you can write above mentioned parts into 4 separate files and just include those in any php file in your project?

Lets say your project has over 100 .php files and all are using same presentation for header, footer, left and/or right navigation and you have included these four parts code into 100 individual pages. What if you have to change some thing in any of the 4 parts, go through each of 100 files…or simply using include statement in each of 100 files and just changing once heander.php, footer.php leftnav.php rightnav.php, for example?

Two types of functions are available to include path of file in PHP.

  1. Include();
  2. Require();

While this chapter only explains about include function, Require() function is covered here.

Syntax of include statement

include(“file_name.php”);

How include statement works

The code of file name referred in calling php file will be copied once there before execution. If there is any problem in loading the file like file name is not correct or specified path is wrong, for example, then a warning message will be generated however script will be executed.

Examples



PHP include file path

Please note all of the 3 files mentioned above should be in same directory as your main .php file where you are referring by using include statement.

If you have include folder, for example then above example would look like this



You can use PHP require  function as well in order to include code of other files.


Was this article helpful?

Related Articles

Leave A Comment?