How to set command line environment variable in PHP shell_exec

17,497

Solution 1

Since environment variables are inherited, setting them inside your script will set them for the commands it launches too. You just have to use putenv.

putenv("VARIABLE=value");

Solution 2

Won't just:

<?PHP
shell_exec('SOMEVAR=SOMEVAL /some/program');

do the trick?

If you're running multiple shell scripts, then putenv is your friend, as zneak pointed out.

EDIT with an exmaple:

env.php:

<?PHP
echo $_ENV['FOO'];
echo "\n";

runenv.php:

<?PHP
echo shell_exec('FOO=bar php env.php');

then try $ php runenv.php

Share:
17,497
Stephen RC
Author by

Stephen RC

Senior developer at Defiant / Wordfence, security analyst, Tolkien fan, and general geek.

Updated on May 01, 2022

Comments

  • Stephen RC
    Stephen RC 4 days

    The script I am trying to run via shell_exec in PHP requires an environmental variable to be set, which afaik is done via:

    export VARIABLE=value
    

    However, to run the script I am forced to do:

    <?PHP
    $sOutput = shell_exec("export VARIABLE=value && my_command_goeth_hereth");
    

    It seams kinda pointless to have to export the variable every time I run any commands.

    Is this the only way to do it, or am I missing a much simpler way?

  • Stephen RC
    Stephen RC over 11 years
    Why is this any different from what I am doing above? i.e. export VARIABLE=value && command
  • timdev
    timdev over 11 years
    it's nearly the same thing. But you don't need to export if you just want the environment to apply to a single script/program. More than one and you're probably better off with putenv()