Web Info and IT Lessons Blog...

Friday 3 April 2015

Dynamically include files in PHP

The previous lesson of PHP lessons series was about File Handling in PHP and in this lesson we will learn how to dynamically include a file in PHP.

Dynamically Include Files in PHP

Normally what we do to include files in PHP is:


include 'file.php';

This will include file.php just fine in the file in which you write this statement but to give your code maturity and dynamic touch, there are better ways to include files. When i say how to dynamically include a file in PHP, i mean the path of the file to be dynamic. In this lesson we will use some of PHP constants to make dynamic path of a file. Let us say we want to include a file named (file.php) lying in the root directory of our project. A dynamic way to do it would be something like this:


include (dirname(__FILE__).DIRECTORY_SEPARATOR."file.php");

In the above PHP code dirname(__FILE__) gives you the directory of the file in which you want to include (file.php). If you are working locally (i.e on localhost) and your file is lying in the root directory of localhost, when we echo dirname(__FILE__) the output will be C:\xampp\htdocs if you have installed xampp in C: drive of your computer. DIRECTORY_SEPARATOR is a pre-defined constant of php which equals to "/" in Unix and \ in Windows, so all it's going to do is put a slash after the root directory path. Finally (file.php) is the filename you want to include and the final path becomes C:\xampp\htdocs\file.php in windows. You should use this method to include your files because it makes your code more mature and dynamic.

For more lessons about PHP subscribe on InformationBitz.com

No comments:

Post a Comment