Woppi
Woppi

Reputation: 5451

PHP including files

What's the difference between

$_SERVER['DOCUMENT_ROOT'];

and

dirname(__FILE__);

I wonder what's the difference because when I 'echo' them, they're returning same path. Which do you prefer should I use and why?

Thanks!

Upvotes: 0

Views: 168

Answers (4)

Martin Bean
Martin Bean

Reputation: 39389

You would normally use $_SERVER['DOCUMENT_ROOT'] when you want to reference your website's root folder from any where within your website or web application.

You will find using dirname(__FILE__) handy if you were including a file, that then needed to include some more files from the same directory. I use this in my PHP wrapper for the Dribbble API

class Dribbble {

    function __construct() {
        require_once(dirname(__FILE__) . '/base.php');
        require_once(dirname(__FILE__) . '/shot.php');
        require_once(dirname(__FILE__) . '/player.php');
    }
}

This means I can just include dribbble.php from any where in my website or web application and not worry about also including base.php, shot.php, and player.php at the same time.

Upvotes: 0

ajreal
ajreal

Reputation: 47321

Both are different

_FILE_

The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, FILE always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.

source : PHP magic constants

Let's said, your document is /var/www,
and your index page is /var/www/index.php

dirname(__FILE__) == $_SERVER['DOCUMENT_ROOT'];

But if you drill-down to sub-folder like /var/www/posts/index.php

dirname(__FILE__) != $_SERVER['DOCUMENT_ROOT'];
/var/www/posts    != /var/www

The use of $_SERVER['DOCUMENT_ROOT'] is more appropriate in this case.

Upvotes: 3

Michal M
Michal M

Reputation: 9480

The former one is a root folder for the HTTP server (or VirtualHost) and it is a server setting.

The latter is the folder containing the current file.

The usage is entirely based on requirements in my opinion.

Upvotes: 0

zerkms
zerkms

Reputation: 254926

__FILE__ always points to the current file path, and $_SERVER['DOCUMENT_ROOT'] points to the document root path ;-)

I prefer first one, as it is more semantic.

If you will try to compare the values of the files, that are located not in your docroot - then you'll get different values.

Upvotes: 2

Related Questions