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

by Yang Yang on February 9, 2010

in PHP Tips & Tutorials

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:

include('include.php');

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

include(dirname(__FILE__).'/include.php');

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:

include('./include.php');

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/appdomain.com/app');

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

include(APP_DIR.'/class/tobeincluded.php');

Thanks to Gumbo, alexef and Justin at Stack Overflow.

Related Posts

Leave a Comment

Previous post:

Next post: