简体   繁体   中英

How to use environment variables in a PHP script using getenv()?

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

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

在此处输入图片说明

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.

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, eg in the vhost section using SetEnv

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM