Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export shell environment variable before running command from PHP CLI script

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?

like image 675
Greg K Avatar asked Mar 09 '12 15:03

Greg K


People also ask

How do I export an environment variable in terminal?

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 ").

How do I export an environment variable in Bash?

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.

What is .env file in PHP?

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 .


1 Answers

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")

like image 155
gymbrall Avatar answered Nov 15 '22 11:11

gymbrall