How to include php files from different directories or folders

php

There are two PHP functions to include one PHP file into another PHP file.

  • The include() Function
  • The require() Function

The include/require statement copies all the text/code/markup from the specified file into the file that uses the include statement. For example we can include the php file example1.php in example2.php. The include and require statements are identical.

The only difference is:
require – produces a compile error (E_COMPILE_ERROR) and stop the script
include – produces a warning (E_WARNING) and continue the script

It is used for including same php code in multiple webpages. For example the ‘comment.php’ file which is used to include comments will be same for all pages.

<?php include('example.php') ?>

It is used to include php file in the same directory

<?php include($_SERVER['DOCUMENT_ROOT'].'/test.php') ?>

It is used to include test.php file located in the root directory (eg. public_html or www folder). The $_SERVER[‘DOCUMENT_ROOT’] is used to set the path relative to root directory.

<?php include($_SERVER['DOCUMENT_ROOT'].'/myfiles/test.php') ?>

It is used to include test.php file located in the myfiles folder of the root directory or folder.