I have a script that uses passthru() to run a command. I need to set some shell environment variables before running this command, otherwise it will fail to find it's libraries.
I've tried the following:
putenv("LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);
Using putenv() doesn't appear to propagate to the command I'm running. It fails saying it can't find it libraries. When I run export LD_LIBRARY_PATH=/path/to/lib
in bash, it works fine.
I also tried the following (in vain):
exec("export LD_LIBRARY_PATH=/path/to/lib");
passthru($cmd);
How can I set a shell variable from PHP, that propagates to child processes of my PHP script?
Am I limited to checking if a variable does not exist in the current environment and asking the user to manually set it?
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
An . env file is a plain text file which contains environment variables definitions which are designed so your PHP application will parse them, bypassing the Apache, NGINX and PHP-FPM. The usage of . env files is popular in many PHP frameworks such as Laravel which has built-in support for parsing .
I'm not 100% familiar with how PHP's exec works, but have you tried: exec("LD_LIBRARY_PATH=/path/to/lib $cmd")
I know that this works in most shells but I'm not sure how PHP doing things.
EDIT: Assuming this is working, to deal with multiple variables just separate them by a space:
exec("VAR1=val1 VAR2=val2 LD_LIBRARY_PATH=/path/to/lib $cmd")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With