1

I'm having trouble using getenv() in my PHP script. I've set the environment variable in my bash session:

MYPATH=~/some/kind/of/path

I've verified it's working with:

echo $MYPATH

My question:

Why is getenv( 'MYPATH' ) returning false when I use it in my PHP web script? I'd expect /home/user/some/kind/of/path to be returned.

Ref: http://php.net/manual/en/function.getenv.php

3
  • Are you running this PHP script from the command line? Commented Feb 9, 2016 at 13:19
  • No. I'm running it through my web server (Apache). I've updated my question to make that clear. Commented Feb 9, 2016 at 13:32
  • Then you need to set the environment variable for Apache.... either add it to your vhosts file or .htaccess file using SetEnv; setting it in your bash will only make it available from the CLI Commented Feb 9, 2016 at 13:34

3 Answers 3

3

If you're setting var and invoking php script right after taht, in the same shell session, you must to export the environment var:

enter image description here

When some variable is exported to environment, it is passed in to environment of all descendents processes. As php creates a new "subprocess" you must share the "environment" and vars with it and this is what happens when using export statement.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not running the PHP script through the CLI, sorry for not making that clear. I've updated my question.
0

If you're trying to access this environment variable through PHP in the web SAPI, then you need to set the environment variable in the configuration for your webserver, e.g. in the vhost section using SetEnv

<VirtualHost hostname:80>
    ...
    SetEnv VARIABLE_NAME variable_value
    ...
</VirtualHost>

1 Comment

It seems I needed to export MYPATH. See 35293297/1709033
-1

If you want to get the file path of the current directory, you can use this:

define("FILE_ROOT", dirname(__FILE__));

Then when you want to use it:

echo FILE_ROOT;

1 Comment

In my case, this isn't what I want to do. But thanks for the suggestion.

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.