Vadzym
Vadzym

Reputation: 157

Access environment variables defined in .htaccess within PHP script called in shell?

I'm trying to print my environment variable defined in .htaccess from PHP script in shell.

My tree is:
/.htaccess (in root folder)
/test/index.php (in "test" folder)

I set my variable in .htaccess with SetEnv:

SetEnv HTTP_TEST "testing"

My PHP script "/test/index.php" is:

#!/usr/bin/php
<?php
echo $_ENV['HTTP_TEST']; // print empty
echo $_SERVER['HTTP_TEST']; // print empty
echo getenv('HTTP_TEST'); // print empty

But if I access my PHP script from my browser there is no problems (without #!/usr/bin/php of course...)

Thank you for any help.

Upvotes: 1

Views: 1010

Answers (1)

Vadzym
Vadzym

Reputation: 157

I built a small PHP script that parse the .htaccess file to find the SetEnv

#!/usr/bin/php
<?php

// Read all lines from file
$htaccess = file('/.htaccess');

foreach ($htaccess as $line) {
    // Trim left/right spaces, replace all repeated spaces by 1 space
    $line = preg_replace('/[ \t]+/', ' ', trim($line));

    // It's our variable defined with SetEnv
    if (substr($line, 0, 7) === 'SetEnv ') {
        $tmp = explode(' ', substr($line, 7), 2);
        $ENV[$tmp[0]] = str_replace('"', '', $tmp[1]);
    }
}

print_r($ENV);

Upvotes: 2

Related Questions