문제

Does the $_SERVER["DOCUMENT_ROOT"] variable exist on IIS running PHP? Earlier I thought this variable is Apache specific and on IIS, you have to emulate it by string manipulation of SCRIPT_NAME and SCRIPT_FILENAME variables but I now see this variable on my PHP installation on IIS. Is it safe to assume that this variable will always be available on IIS.

도움이 되었습니까?

해결책

Is it safe to assume doc root is always available in IIS? No...

$_SERVER['DOCUMENT_ROOT'] is not always available on IIS.. it has to be set in the config file...

If it is configured on your server you 'could' use it... Just make sure your config file doesn't change - otherwise you will break your scripts...

다른 팁

IIS doesn't always set $_SERVER['DOCUMENT_ROOT']

How do you set it in a configuration file, so the rest of your code works like on Apache servers?

Output $_SERVER to see what IS given that you might be able to use:

echo "<br>_SERVER:<br><pre>";
print_r($_SERVER);
echo "</pre><br><br>_ENV:<br><pre>";
print_r($_ENV);
echo "</pre><br><br>";

In this case, the SCRIPT_FILENAME and SCRIPT_NAME are set.

Modify the code below to use what is given to get DOCUMENT_ROOT:

if (!isset($_SERVER['DOCUMENT_ROOT']) || $_SERVER['DOCUMENT_ROOT'] === '') {
    $_SERVER['DOCUMENT_ROOT'] = substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));
    putenv('DOCUMENT_ROOT='.$_SERVER['DOCUMENT_ROOT']);
}

Now you can use $_SERVER['DOCUMENT_ROOT'] normally:

$docroot = getenv("DOCUMENT_ROOT"); 
include_once "$docroot/folder/yourfile.php"; 

I solved it by simply referencing my web root, and setting it as one of my own variables.

<?php
echo getcwd();
chdir('/');
echo getcwd();
chdir('/example-web-server');
echo getcwd();
?>

The following code gets the current working directory of PHP, which will be the directory containing the file you're running this on. chdir('/') goes to the root of wherever PHP can operate, in my case C:\. My example web server's web root is at C:\example-web-server, so you can reference it in PHP like this: /example-web-server.

Once you've got the path for PHP, you could set it as a variable and call it. I'll use an example of an include() of C:\example-web-server\testing\index.php:

<?php
$webroot = "/example-web-server";
include("{$webroot}/testing/index.php");
?>

I know this is an old thread, but I can't be the only one needing a solution for this.

This is what I did on top of index.php:

if(!isset($_SERVER["DOCUMENT_ROOT"]))
{
    $_SERVER["DOCUMENT_ROOT"]=getcwd();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top