Php – Inconsistent trailing slash in DOCUMENT_ROOT variable in PHP when using Apache

apache-2.2configurationdocumentrootPHP

In different server environments, the PHP $_SERVER['DOCUMENT_ROOT'] super global sometimes has a trailing slash and sometimes it does not. I would have thought this issue is directly related to how the Apache DocumentRoot is defined in the httpd.conf file:

i.e. I would have thought that if httpd.conf contains no trailing slash:

<VirtualHost *:8880>
    DocumentRoot /var/www/live/current
    ...

then echo $_SERVER['DOCUMENT_ROOT'] should give /var/www/live/current

and if httpd.conf does contain a trailing slash:

<VirtualHost *:8880>
    DocumentRoot /var/www/live/current/
    ...

then echo $_SERVER['DOCUMENT_ROOT'] should give /var/www/live/current/

This is the case on Ubuntu 10.04 but on RHEL 5.5 a trailing slash is added to $_SERVER['DOCUMENT_ROOT'] even if none was defined on Apache.

Any idea why this happens? Is there a configuration parameter that I'm missing?


For reference:

  • PHP 5.3.3 of RHEL (issue occurs): PHP 5.3.3 (cli) (built: Jul 23 2010 16:26:53)
  • PHP version of Ubuntu (no issue): PHP 5.3.2-1ubuntu4.2 with Suhosin-Patch (cli) (built: May 13 2010 20:03:45)

Best Answer

I have no idea why the slash is changing between your virtual hosts. By the way, is it important ? Just add a new slash to your programs (remove if a double slash is present) and the problem is solved.

I use

$realpath = realpath ($_SERVER['DOCUMENT_ROOT']."/");
$realpath = str_replace ("//", "/", $realpath);
Related Topic