Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use $_SERVER['DOCUMENT_ROOT'] in includes?

Tags:

php

Is this, for example, a good idea?

require_once($_SERVER['DOCUMENT_ROOT'].'/include.php');

If you have two virtual hosts on the same server, one for live and one for development, with different Apache DocumentRoots, this would avoid having to include absolute paths when the source of the include is unknown, and may be in any directory.

(Note: file paths in the following section are relative to the web root. They would in fact be like /var/www/app/core/init.php, where /var/www/app is the web root)

For instance: I have an /core/init.php which is called using relative paths from places all over the website (/file.php, /dir/file.php or /dir/dir/file.php).

This init.php then includes several function pages, in the fund directory, a subdir of /core (as in /core/func/userfunctions.php).

So, in init.php, I can use the $_SERVER method, because it breaks if I use a relative path and try to call functions from a page like /dir/file.php.

I can't see any problem with it, but in general what could go wrong?

like image 203
Alfo Avatar asked Aug 10 '12 00:08

Alfo


People also ask

What is $_ server [' DOCUMENT_ROOT '] in PHP?

$_SERVER['DOCUMENT_ROOT'] returns. The document root directory under which the current script is executing, as defined in the server's configuration file.

What is $Document_root?

The document root is a directory (a folder) that is stored on your host's servers and that is designated for holding web pages. When someone else looks at your web site, this is the location they will be accessing.


2 Answers

I've seen cases where $_SERVER['DOCUMENT_ROOT'] is not set or is not what you would expect (i.e. not set in CLI or old IIS, or invalid in certain CGI setups).

For that reason you can use dirname(__FILE__) to obtain the path of the script that line is called in. You can then reference relative paths from there e.g.

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

I go with the above method when the directory structure of the files is known and is not subject to change.

If DOCUMENT_ROOT is not available, the following is a suitable replacement:

substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));
like image 99
drew010 Avatar answered Oct 21 '22 15:10

drew010


You don't need to do this. PHP looks for the included file in the document root by default.

You can use set_include_path($new_include_path) to change this behaviour, or edit include_path in the php config file.

Also, from http://php.net/manual/en/reserved.variables.server.php:

'DOCUMENT_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file.

like image 22
NotGaeL Avatar answered Oct 21 '22 16:10

NotGaeL