PHP: Why you should use dirname(__FILE__).‘/include.php’ instead of just ‘include.php’

When you need to include or require a php file that is in the same directory as the currently running one, most people come up with this simple line in the current script:


While this approach doesn’t present obvious breaches, it is slightly inefficient than the following way:


You will type a little more but the extra code frees PHP from iterating through the include_path in the attempt to locate ‘include.php’ because dirname(__FILE__) has explicitly returned the absolute path to the file. The constant __FILE__ in PHP always returns the absolute path to the script file that’s currently active – the PHP file in which the code line is being run right now. Function dirname() returns the directory part of the given path.

A better approach would be:


Which explicitly commands PHP to look for the file ‘include.php’ in the current directory, yet comes without the overhead of the function dirname(). With large applications, you would prefer storing the path of the primary working directory of the application in some centralized configuration files:

define('APP_DIR', '/home/appuser/');

And when you need to include a file in the sub directory ‘class’:


Thanks to Gumbo, alexef and Justin at Stack Overflow.

5 thoughts on “PHP: Why you should use dirname(__FILE__).‘/include.php’ instead of just ‘include.php’”

  1. Why not just do define(‘APP_DIR’, dirname(__FILE__)); ? That why you don’t have the overhead cause it is only called once but you can always move your app around

  2. good tutorial!! Now I know how to use __file__
    For example,


    means you are checking whether the offline.php in the same directory exists!!If it exists, do something to output an offline page!

  3. Just to explain the need for this, which seems to have been omitted.

    The current directory is the directory of the running SCRIPT not the directory of the FILE.

    So if you chain your includes, they may not be found.
    ie. ‘home.php’ includes’ includes.php’, which is fine as they are both in the same directory.
    HOWEVER ‘subdir/home.php’ includes ‘../home.php’ (which fails to include ‘includes.php’ as subdir is now the current directory and ‘subdir/includes.php’ does not exist)

Comments are closed.

Scroll to Top