Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to set PHP $_SERVER['DOCUMENT_ROOT'] Trailing Slash?

Tags:

php

apache

ubuntu

Sometimes $_SERVER['DOCUMENT_ROOT'] returns with a trailing slash. In other environments it does not. Where can this be specified?

like image 938
cars Avatar asked Mar 12 '12 18:03

cars


3 Answers

You can not say in advance if $_SERVER['DOCUMENT_ROOT'] contains a slash at the end or not.

Normally, if properly configured, it does not contain a trailing slash. On Ubuntu (as well as on other UNIX), a properly written path to a directory does not have the / at the end. On windows for example, apache will even refuse to start if it's configured with one. On UNIX Apache is not that picky and allows with a trailing slash.

But there is one exception, if you make your root directory (/) your document root. Because of that case, you can not say in advance whether or not it contains a trailing slash.

In any case it contains the value of the DocumentRoot directive - with or without trailing slash like it has been written into the httpd configuration file. PHP only takes over the value from apache. To get the real document root, use realpath and/or conditionally add a slash (or remove it) at the end if either in your configuration file or within your PHP code.

like image 112
hakre Avatar answered Nov 19 '22 01:11

hakre


I tend to use the current directory more than I use docroot because it also works well on command line and in unit tests too. I tend to use something like:

require_once(dirname(__FILE__).'/../../../../constants.php');

Rather than:

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

I saw it first in Wordpress source and quite liked it, but it can lead to a lot of '../' repetition.

P.S. FILE is the current file and dirname will strip off the /something.php from the end therefore leaving the path of the directory containing the current file.

like image 25
MatCarey Avatar answered Nov 19 '22 01:11

MatCarey


You can do like this, in order to make sure the trailing slash is always present

'/'.trim( $_SERVER['DOCUMENT_ROOT'], '/' ).'/'

require_once( '/'.trim( $_SERVER['DOCUMENT_ROOT'], '/' ).'/'.'constants.php' );
like image 3
Sergey Onishchenko Avatar answered Nov 19 '22 02:11

Sergey Onishchenko