phpiisdocument-root

How to get a working DOCUMENT_ROOT value on IIS server?


I've been working with Linux servers I think about 98% of my development time. And for more or less the first time I'm putting code onto some IIS server.

I work on a Linux Env so everything works as I'd expect it to, however getting to the IIS server and everything falls apart. I'll save everyone a massive rant about why IIS and Windows sucks and get to the issue in hand.

Use of $_SERVER['DOCUMENT_ROOT'] on my env outputs a value like:

/var/www/project

Which is good for including files e.g.

require_once $_SERVER['DOCUMENT_ROOT']. '/app/connect.php';

However, on IIS this errors with the message:

No such file or directory

This made me prefix the code with this:

echo '<pre>'. print_r($_SERVER['DOCUMENT_ROOT'], 1) .'</pre>';

which outputs this:

C:\inetpub\wwwroot

100% unrelated to the actual site.

Is there an IIS-specific variable I should be using to include my scripts? It seems to have a huge knock-on affect for all of my code when including files which isn't ideal at all. In a dream world, my code wouldn't touch IIS with a 10-foot pole but unfortunately it has to run on it.

How do I set the root for the site in my code?


Solution

  • Unfortunately for me, the IIS server isn't in my control so I couldn't really look to solutions that tamper with the server settings. However I did manage to find a solution:

    I placed in my header.php template file:

    echo '<pre>'. print_r(exec('CHDIR'), 1) .'</pre>';
    

    this gave me a value that looked like this:

    C:\www\mysite

    Which is a lot different to the output of $_SERVER['DOCUMENT_ROOT'].

    I created a conditional to tell the server OS apart and set a new variable based on the value:

    if (strpos(PHP_OS, 'Linux') > -1) {
        $root = $_SERVER['DOCUMENT_ROOT'];
        $feRoot = '/';
    } else {
        $root = 'C:\\www\\mysite';
        $feRoot = 'http://mysite';
    }
    

    Now I can call my scripts like this ($DS = DIRECTORY_SEPRARTOR):

    require_once $root. $DS .'app'. $DS .'connect.php';
    

    And call my frontend assets like this:

    <link rel="stylesheet" href="<?php echo $feRoot; ?>/css/file.css" />
    

    So the key to IIS is deal in absolutes rather than relative to the DOCUMENT_ROOT