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.
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 ...');
To add a path to the PATH environment variableIn the System dialog box, click Advanced system settings. On the Advanced tab of the System Properties dialog box, click Environment Variables. In the System Variables box of the Environment Variables dialog box, scroll to Path and select it.
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 .
$_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.
In order of preference:
/usr/local/bin/wget
when you are calling the subprocess. This is probably the simplest and best approach.proc_open
instead of exec
, which allows you to pass environment variables as an argument.putenv
to change the current environment (which will be inherited by subprocesses).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
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