1

Im trying to define the absolute root path and the root url of my app. I tried this, however I can't understand something yet.

I have created config.inc.php in the root folder with the code in the answer. Also I have the file index.php in the root in which I include config.inc.php and the constanst are fine. But I have another file in ${ROOT}/example/file.php where I also include config.inc.php but the root url contains the example folder in the end.

The app structure is:

config.inc.php
index.php
example/file.php

How can I always have the absolute root path and the root url of my app?

Thanks!

Community
  • 1
  • 1
gonzalomelov
  • 971
  • 1
  • 13
  • 30

4 Answers4

4

Absolute root path:

$_SERVER['DOCUMENT_ROOT']

Path from the root folder:

dirname($_SERVER['PHP_SELF'])
Antony
  • 14,900
  • 10
  • 46
  • 74
  • It seems like dirname($_SERVER['PHP_SELF']) is the best to use, because it can be used for both appending to the beginning of URL's, and appending to includes files... Although it is not creating an "absolute" url/path, it creates a relative path that will work on any server if you put it in the config file in the root folder. – Andrew May 13 '14 at 15:16
  • define('ROOT', dirname($_SERVER['PHP_SELF'])); – Andrew May 13 '14 at 15:18
0

You can manually type an absolute and root url in config file and when include it he give you an variable with absolute and root url. For root directory you can use an $_SERVER['DOCUMENT_ROOT'].

codercat
  • 22,873
  • 9
  • 61
  • 85
mrakodol
  • 1,143
  • 3
  • 12
  • 41
  • The fact of changing the config everytime I deploy the app in a diferent server is considered bad practice? – gonzalomelov Feb 04 '13 at 19:29
  • if you set an variables whic is set to $_SERVER['DOCUMENT_ROOT'] you did not need to change it on every new deploy on other server, because he get an document root on that server. – mrakodol Feb 04 '13 at 19:32
0

I've always used the following code in my php apps:

** config.php **

$base = str_replace(
    $_SERVER['DOCUMENT_ROOT'],
    '',
    realpath(dirname(__FILE__)));

$base = ($base == '') ? '/' : '';

You can include this file from anywhere and it will give the base uri of the folder config.php is in.

Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
0

if you are working with files on windows then you might need to use both like

$full_path = $_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF']);
user889030
  • 4,353
  • 3
  • 48
  • 51