If your code is including other files, you will encounter problems like “The file is not found”. This is because, PHP doesn’t know the absolute path of file. So, if you are including files on another file, you should mention the absolute path of file.
But, If you’re PHP application is being used by other people, then the absolute path which you mentioned in your system won’t be the one of the others’ systems. So, you have to dynamically mention the absolute path that will work on any systems.
Example of Problem
Here is one of the case scenarios where you encounter the include problem.
Suppose, the index.php file is including the file1.php which is in the inc directory :
<?
include("inc/file1.php");
?>
The inc directory also contains other files such as file2.php, file3.php, file4.php etc……. If you want to include the file2.php in file1.php like below, it won’t work :
<?
include("file2.php");
?>
In file1.php, the root directory is that of index.php. Because we are including the file1.php from index.php which is outside the directory.**
**
I think you understand the problem. Luckily, I have a solution that fixes this problem.
Solution of Problem
Since PHP 4.0.2, __FILE__ returns the absolute path of the running script even if it’s an include file. By giving the __FILE__ constant to the dirname function, you will get the directory of the script. So, code in file1.php would become :
<?
include(dirname(__FILE__)."/file2.php");
?>
The version 5.3.0 and it’s later versions have a new constant called __DIR__ which is the short way of dirname(__FILE__). You can also use this in replacement of what we used earlier. Now code in file1.php will become :
<?
include(__DIR__."/file2.php");
?>
You can see more PHP Magic Constants in this manual page.