6

I have a PHP script that is using wget to download some images. However, wget was installed using Homebrew so it's not available to the user running the PHP script. When I run exec('echo $PATH') I don't get the /usr/local/bin directory that contains wget. How do I add /usr/local/bin to the environment path so the PHP script can find wget?

Update: I forgot to mention the reason I can't specify the exact location is because the location may be different depending on which machine this script is being run on.

Solution:

This is what I ended up with:

//help PHP find wget since it may be in /usr/local/bin
putenv('PATH=' . getenv('PATH') . PATH_SEPARATOR . '/usr/local/bin');
if (exec('which wget') == null) {
    throw new Exception('Could not find wget, so image could not be downloaded.');
}

//now we know wget is available, so download the image
exec('wget ...');

2 Answers 2

9

In order of preference:

  1. You can simply specify the full path /usr/local/bin/wget when you are calling the subprocess. This is probably the simplest and best approach.
  2. You can use proc_open instead of exec, which allows you to pass environment variables as an argument.
  3. You can use putenv to change the current environment (which will be inherited by subprocesses).
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, is putenv valid only for the current request? New request won't have the new added path, correct?
The PHP documentation indicates it does not survive beyond the current request.
2

PHP has a magic global variable called $_ENV which is an array holding all environment variables (in the context of the process the PHP script runs in, e.g. your web server).

see http://php.net/manual/en/reserved.variables.environment.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.