Thursday, May 28, 2009

PHP relative include solution

I does not matter how much a advanced or experienced PHP developer you are to know the strange behavior in PHP's include or require paths. Sooner or later as you code grows larger and larger you will split your code in many smaller include files. And then one include file will include another include file which is in a different path. If you include the first include file(that includes another php) and you just used relative paths then you will face the problem. You cannot use a relative path because the paths in include and require commands are relative to the main php file the includes everything.

Ok it seems complicated but lets give an example. We have this directory structure.

[root]

include_a.php --> include "a/a.php";
main.php --> "include_a.php"
;
[a]
---- a.php

[d]
---- d.php --> include "../include_a.php";

In this example we have a php named include_a.php that includes a php named a.php in a folder named a. Please notice that the include path is relative. If you used absolute paths you will have no problems but it is better if your code was not depended in the install location.
The the main.php includes the include_a.php and main.php will run without errors. But let's see what will happen with d.php that rests in d folder. It also includes include_a.php and include_a.php includes a.php in folder name a. If you execute d.php you will get an error saying the a.php cannot be found. Why? Because the d.php will try to include a.php(via include.php) in folder a that will be a sub folder of folder named d in which the main execution php file rests. So every relative include is relative to the main php execution file.
So is the absolute paths the only solution to this problem. No.
You can still have all your code location independent in php. How?
The __FILE__ constant is your solution. The __FILE__ constant always point the full pathname of the php file that uses __FILE__(and not the main php execution file). So by using the line below you can include a php in a relative path.

include dirname(__FILE__)."relative_path";

The dirname is a useful function that will extract the directory component of a full file path and then you can insert the rest of the relative path.
So change the include "a/a.php" to include dirname(__FILE__)."a/a.php" in include_a.php and your d.php will run without errors.

No comments:

Post a Comment