PHP unable to access /etc/environment variables only trough browser

360 views Asked by At

I'm facing an issue where php or apache is unable to load variables from /etc/environment, and only if php code is run trough browser.

I have the php-fpm/www.conf clear_env set to no

clear_env = no

and line added to /etc/sysconfig/php-fpm

EnvironmentFile=/etc/environment

After restart I'm able to see variables when running

php -r "print_r(\$_ENV);"
sudo -u apache env
sudo -u apache php -r "print_r(\$_ENV);"

But if I open test.php in the browser they are not there

<?php
 $output = shell_exec('env');
 echo '<pre>';
 echo $output;
 print_r($_ENV);
 print_r($_SERVER);
 print_r(getenv());
 echo '</pre>';
 phpinfo();
?>

I cannot for my life figure out why it only fails on browser where clearly apache user can see variables from /etc/environment

UPDATE

I was unable to work out why it would work on one vm and not the other. So decided to go a different way. I now inject environmental variables to /etc/php-fpm.d/env.conf when there is a change in /etc/environment, using below script:

fpm_file="/etc/php-fpm.d/env.conf"
if [[ ! -f "$fpm_file" ]]; then
    sudo touch $fpm_file
    echo '[www]' | sudo tee -a $fpm_file > /dev/null
fi
i=0;
if [[ -f "$fpm_file" ]]; then
    vars=$(sudo grep -v '#' /etc/environment | sed '/^[[:space:]]*$/d' | sed -e 's/^/env[/' | sed 's/=/]=/g')
    while read -r line; do
        chk=$(grep -F "$line" $fpm_file | wc -l )
        if (( "$chk" == 0 )); then
            echo "$line" | sudo tee -a $fpm_file > /dev/null
            ((i++))
        fi
    done <<< "$vars"
    if (( "$i" > 0 )); then 
        echo "New enviromental variables found, added to php, restarting php-fpn..."
        sudo service php-fpm stop
        sleep 5
        sudo service php-fpm start
        echo "All done!"
    fi
fi

I run that script via .bashrc on login. That works well and I can maintain env vars in one file instead of multiple. Not adding this as answer as the original issue is still present and unresolved.

1

There are 1 answers

2
Crue On

You are using php script from browser means you are using web server like apache or nginx. If you are using apache then you need to set env varaibles in apache vHost file using SetEnv keyword like below

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin [email protected]
        ServerName api.example.com
        ServerAlias api.example.com
        DocumentRoot /vagrant/codebase/example

        SetEnv APPLICATION_ENV production
        SetEnv APPLICATION_CONFIG user

    </VirtualHost>
</IfModule>

.

In nginx you need to set like below

location / {
...
   fastcgi_param   APPLICATION_ENV  production;
   fastcgi_param   APPLICATION_CONFIG user;
...
}

Hope this helps