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.


Facebook
Twitter
Google Plus
{ 2 comments… read them below or add one }
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
If you are on php 5.3+, you can use __DIR__ instead.