Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set command line environment variable in PHP shell_exec

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?

like image 700
Stephen RC Avatar asked Aug 26 '10 02:08

Stephen RC


People also ask

What is Shell_exec function in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix. If the command fails return NULL and the values are not reliable for error checking.

Does PHP wait for Shell_exec to finish?

Some of the scripts that the queue runner script executes may take 30 seconds or so to finish running (generating PDFs, resizing images, etc). The problem is that shell_exec() in the queue runner script calls the processing scripts, but then doesn't wait for them to finish, resulting in the queue not being completed.

What is $_ ENV in PHP?

Introduction. $_ENV is another superglobal associative array in PHP. It stores environment variables available to current script. $HTTP_ENV_VARS also contains the same information, but is not a superglobal, and now been deprecated. Environment variables are imported into global namespace.


1 Answers

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");
like image 178
zneak Avatar answered Sep 25 '22 03:09

zneak