This is an exension to this question where we learn that we can set a $_SERVER
var using SetEnv
.
The next question is: Is there a way to use SetEnv essentially like this:
/var/www/www.example.com/module/unique_section/.htaccess:
SetEnv RESOURCE_ROOT %{DIRECTORY}
/var/www/www.example.com/module/unique_section/some/path/file.php
<?php echo $_SERVER['RESOURCE_ROOT']; ?>
Output: /var/www/www.example.com/module/unique_section/
Depending on the information you require, you may be able to do this with a RewriteRule
. For example:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT} (.*)
RewriteRule (.*) - [E=RESOURCE_ROOT:%1]
will set the PHP var $_SERVER['RESOURCE_ROOT']
or $_SERVER['REDIRECT_RESOURCE_ROOT']
to your Apache Document Root. See the mod_rewrite manual for full details, but some combination of %{DOCUMENT_ROOT}
, %{PATH_INFO}
and %{REQUEST_FILENAME}
may work for you.
I don't think it's possible for the .htaccess
file to know what directory it resides in. So I think you'll need to use hardcoded paths inside your .htaccess
file. As an example:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT} (.*)
RewriteRule (.*) - [E=RESOURCE_ROOT:%1/module/unique_section/]
as far as I can tell, setEnv doesn't have access to the apache environment variables. So the %{DIRECTORY} wouldn't work unless you wanted the value to be specifically "%{DIRECTORY}". Using mod_rewrite, this worked for me to get the path of the file being loaded:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} ((.*)/)
RewriteRule (.*) - [E=RESOURCE_ROOT:%1]
outputs:
var_dump(__FILE__);
//outputs: string(27) "/var/www/sub/test/index.php"
var_dump($_SERVER['RESOURCE_ROOT']);
//outputs: string(24) "/var/www/sub/test/"
Other than that, is there anything wrong with just using php and doing dirname(__FILE__)
or dirname($_SERVER['PHP_SELF'])
?
You can use the function apache_getenv
to get what you want.
Link : http://php.net/manual/en/function.apache-getenv.php
Do not forget to read the documentation :
This function requires Apache 2 otherwise it's undefined.
Example :
<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>
The above example will output something similar to:
42.24.42.240
But, as suggested in this threat, you could just use dirname(__FILE__)
and since PHP 5.3.0 you can use __DIR__
as a magic constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With