As already explained, it uses variable $_SERVER
, you should not expect all browsers/systems to return the same thing, because some of these sometimes omit information, but what I say is, use this variable only to find out which is the directory root you are currently using or will use, directly using that variable or based only on the path it returns.
In the console/terminal of commands, of course it will not return the path, but if you run from a browser you will be able to view this path, which by chance is a path defined in the server configuration file.
In a system linux recent, you will get /var/www/meu_site
, using $_SERVER['DOCUMENT_ROOT']
.
Based on this, you can simply define all possible paths for your application in a single configuration file, which is(ia) called once.
// init.php
// Ficheiro de inicialização de configurações gerais
define('DS', DIRECTORY_SEPARATOR);
define('ROOT',$_SERVER['DOCUMENT_ROOT']);
define('SITE_ROOT',ROOT.DS.'meu_site');
# 2º alternativa
# define('SITE_ROOT',DS.'var'.DS.'www'.DS.'meu_site');
define('LIB_CLASS',SITE_ROOT.DS.'classes');
define('LIB_INCLUDES',SITE_ROOT.DS.'includes');
So just include this file in the script:
require_once '/includes/init.php';
// Noutros ficheiros que possuam a configuração de inicialização
print "<h3>Diretórios:</h3>";
print SITE_ROOT.DS.'teste.php';
//require_once SITE_ROOT.DS.'teste.php';
print "<br/>";
print LIB_CLASS.DS.'class.teste.php';
//require_once LIB_CLASS.DS.'class.teste.php';
print "<br/>";
print LIB_INCLUDES.DS.'testeValidar.php';
//require_once LIB_INCLUDES.DS.'testeValidar.php';
The paths will be like this:
/var/www/meu_site/teste.php
/var/www/meu_site/classes/class.teste.php
/var/www/meu_site/includes/testeValidar.php
For windows, you will obviously get different paths and
different separators as well, but this is the idea.
Utilizes the $_SERVER['DOCUMEN_ROOT'], and creates a constant DIR based on that address.
– Edilson
If you will use in the terminal
$_SERVER['DOCUMEN_ROOT']
will come empty. However as you are saying that you want the root of the document, then it is understood that you want to use via web server. So I suggest that you create a constant that points to the root directory at the beginning of the code, or in your application’s configuration file. So in any subsequent file you will have this constant available. The constant will work for both command line calls and web server calls.– Diego B. Sousa