phpfilepathstr-replacedocument-rootpath-separator

Getting Server's Root Path


Getting the root to the site's folder isn't difficult but I am trying to get the folder in which all sites are located rather than the root folder of a specific site. I have been using the code below but I came across an instance affecting $CommonPath where it isn't working due to one site's specific structure.

In other words, one of my Windows development systems has something like:

C:\Server\Sites\site1.loc
C:\Server\Sites\site2.loc
C:\Server\Sites\site3.loc

and another Linux-based development system has:

/var/www/html/site1.loc
/var/www/html/site2.loc
/var/www/html/site3.loc

and I am trying to fetch C:\Server\Sites\ or /var/www/html/ from code that is inside a subfolder or two from these roots. How is it done without having to specify which subfolder the variable is being created in?

$SiteFolder = @end(explode(DIRECTORY_SEPARATOR, dirname(__DIR__)));
$CommonPath = str_replace($SiteFolder,"",dirname(__DIR__)) . "common" . DIRECTORY_SEPARATOR;
$ConfigPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . "configuration" . DIRECTORY_SEPARATOR;
$FunctionsPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . "functions" . DIRECTORY_SEPARATOR;

Solution

  • I finally got it working by first creating a variable for the site's root, then exploding on the directory separator and getting only the last bit, then filtering it out of the path. Perhaps it's not the most elegant code but it seems to work.

    $dirSeparator = DIRECTORY_SEPARATOR;
    $serverRoot = str_replace("/",$dirSeparator,$_SERVER['DOCUMENT_ROOT']);
    $SiteFolder = end(explode($dirSeparator,$serverRoot));
    $CommonPath = str_replace($SiteFolder,"",$serverRoot);
    

    I'm not sure why I was unable to use DIRECTORY_SEPARATOR directly but creating a variable for it did work. Also, and possibly a PHP bug, using $_SERVER['DOCUMENT_ROOT'] on a Windows server still gives Linux directory separators so I had to do a str_replace() to work that out.

    The reason I needed to do all this was to be able to include files with functions common to several sites that are in an aliased folder so my actual code is like this:

    $CommonPath = str_replace($SiteFolder,"",$serverRoot) . "common" . $dirSeparator;