How to unset an environment variable using php?
Asked Answered
P

1

13

I know I can set an environment variable using

putenv("ENV_FOO=SOMETHING");

and get the value via:

getenv("ENV_FOO");

If the variable isn't set, getenv("ENV_FOO") will return false.

I have a feature set that may be set via an environment variable, and I wanted to unit test the behavior when the variable is set or not set.

Yet once export the variable on my dev machine in bash via

export ENV_FOO=something`

it breaks my unit test, as I cannot unset the environment variable using php for the scope of the test.

I tried putenv("ENV_FOO="); yet this will return in an empty string "", not in an unset environment variable for the current shell session.

Is there a way to unset an environment variable for the current shell session, or do I have to change the way I test for the existence of the variable?

Perforated answered 3/12, 2015 at 11:54 Comment(0)
S
32

Try this from the putenv docpage comments

<?php
putenv('MYVAR='); // set MYVAR to an empty value.  It is in the environment
putenv('MYVAR'); // unset MYVAR.  It is removed from the environment
?>
Senescent answered 3/12, 2015 at 11:59 Comment(3)
It didn't work for me. Then I realized again that I am using hhvm which has a bug of this not working: github.com/facebook/hhvm/issues/2533Perforated
sorry to hear this :( you can try shell_exec("unset FOO"); if you haven't set the env. variable from withing php itself, might workSenescent
I attempted this approach in a docker container on PHP 7.0 with no luck, the env var value was still set once the container was built.Firestone

© 2022 - 2024 — McMap. All rights reserved.