Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading user environmental variable in php

I have an environmental variable defined in Windows environmental variables -> user variables

$MY_VARIABLE=mypath

and in php I tried to access it like below

<?php
echo $_ENV["MY_VARIABLE"];

but it doesn't print anything. Am I missing something here or is it that PHP doesn't have access to user environmental variables ?

EDIT: I am running PHP as an Apache module (important info that I left out initially).

like image 694
Krishnaraj Avatar asked Oct 06 '12 13:10

Krishnaraj


2 Answers

You $_ENV is empty because of variables_order settings in PHP

Edit your PHP.INI

Change

  variables_order = "GPCS"

To

 variables_order = "EGPCS"

It should work by now if it does not try using .htaccess to achieve this

Add the following to your .htaccess

SetEnv foo bar

You can get it via PHP

var_dump(getenv('foo'),$_ENV);
like image 99
Baba Avatar answered Oct 20 '22 12:10

Baba


Recently i wrote a library to get values from environment variables and parse to the PHP data types. This library can be used to parse environment variables to PHP data types (like the casting to integer, float, null, boolean), parse the complex data structures like a JSON string and more with the contribution of the commnunity.

The library is available here: https://github.com/jpcercal/environment

And to get the values from environment variable to do it:

<?php
// ...
require "vendor/autoload.php";
// ...
var_dump(Cekurte\Environment\Environment::get("MY_VARIABLE"));

Enjoy it.

like image 1
João Paulo Cercal Avatar answered Oct 20 '22 12:10

João Paulo Cercal