问题
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.
回答1:
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...
回答2:
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";
回答3:
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.
回答4:
This is what I did on top of index.php:
if(!isset($_SERVER["DOCUMENT_ROOT"]))
{
$_SERVER["DOCUMENT_ROOT"]=getcwd();
}
来源:https://stackoverflow.com/questions/4577853/document-root-variable-on-php-iis