Changing PATH in my .bashrc isn't reflected in my php environment

I modified my .bashrc like this:

export PATH=xx:$PATH

If I type “echo $PATH” from my ssh shell file, the path indeed begins with “xx:”. Great.

I have a webpage which invokes php (set up to php 7 if it matters, with an empty phprc). I added this line inside my php directives:

echo "My PATH is ." . $_ENV["PATH"] . "'"; 

When I visit the corresponding html page, I do see the message, but the reported path is

My PATH is '/usr/local/bin:/usr/bin:/bin'

Can anyone tell me why php isn’t picking up the PATH I set in my .bashrc? Or clue me in where to look?

Obviously, I don’t really care about xx in the path, but that is just a stand-in for my real issue, which is more complicated. If you want to know the real story, this php-infected html page actually invokes a python script, and that script is not seeing the PATH and PYTHONPATH env variables it needs in order to pick up my virtualenv. But I believe if I can solve the above “xx” path problem, it will lead me to the solution of my actual problem.

Thank you.

On DreamHost, PHP scripts are executed by a PHP process (typically php70.cgi) that is launched on-demand by Apache. Although the PHP process runs as your user, its environment is setup by Apache, which includes a default minimal PATH. The Bash shell isn’t involved in running PHP scripts, so your .bashrc is not loaded. You can see PHP’s full environment via phpinfo().

There are a variety of solutions, but one simple one is to run your Python script via a Bash launcher script. This ensures that the Python script runs in an environment similar to a command-line shell.

Here’s what a launcher.sh script might look like (untested code):

#!/bin/bash
# Bash will load .bashrc, so custom PATH, etc. are now available.
 
# tail exec to replace Bash process with Python, for efficiency.
exec python myscript.py

From PHP, you might call this with:

system('launcher.sh');

Hope that helps.

1 Like

Fantastic reply, habilis. That is exactly the information I needed. I’m sure the information is out in the googlesphere, but there is so much information out there I didn’t find that fact in the haystacks I was looking in.

Thanks again, habilis, that worked. The only other trick was that I’m uploading from a windows machine, and files don’t have the same permissions as on unix systems, so I had to manually set execute permissions on the launcher shell to get it to run.

Great. If permission setting proves annoying, you could explicitly invoke Bash with the shell script. Then launcher.sh won’t need to executable. Example:

system('bash launcher.sh');
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.