Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a DYNAMIC Php $_SERVER value ($_SERVER['something']) using Apache .htaccess

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/

like image 965
Nathan J.B. Avatar asked Jun 28 '12 20:06

Nathan J.B.


3 Answers

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/]
like image 87
Josh Avatar answered Nov 14 '22 21:11

Josh


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'])?

like image 31
Jonathan Kuhn Avatar answered Nov 14 '22 22:11

Jonathan Kuhn


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.

like image 34
David Bélanger Avatar answered Nov 14 '22 21:11

David Bélanger