PHP getenv始终返回false [英] PHP getenv always returns false

查看:129
本文介绍了PHP getenv始终返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getenv()始终返回false.我正在使用Symfony dotenv库,并从项目根目录中的.env文件加载变量.

The getenv() always returns false. I am using Symfony dotenv library and loading my variables from a .env file in the root of my project.

use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\Dotenv\Exception\PathException;

if (!getenv('APP_ENV')) {
    try {
        (new Dotenv())->load(__DIR__ . '/../.env');
    } catch (PathException $ex) {
        echo $ex->getMessage();
        exit(1);
    }
}

var_dump(getenv('APP_ENV')); // bool(false)

但是当我转储超级全局变量时,我可以看到我的变量

But when I dump the super global I can see my variables

var_dump($_ENV); // array:1["APP_ENV" => "dev"]

那我想念什么?

推荐答案

我没有使用symfony,但是遇到了一些问题我正在使用vlucas库,这是导致问题的我的第一个代码

I m not using symfony but i've encountered the some problem i am using the vlucas library this is my first code that caused the problem

define('BASE_PATH',realpath(__DIR__.'/../../'));
require_once __DIR__.'/../../vendor/autoload.php';
$dotEnv = Dotenv\Dotenv::createImmutable(BASE_PATH);
$dotEnv->load();
$appName=$_ENV['APP_NAME'];
$appName2=getenv('APP_NAME'];

var_dump($appName) // return "This is my website";
var_dump($appName2) // return false;

一开始我没有弄清楚问题,但似乎是因为putenv()和getenv()不是线程安全的

i didn't knwo the problem at first but it seems that it was because putenv() and getenv() are not thread safe

所以我将其更改为此代码

so i changed it to this code

define('BASE_PATH',realpath(__DIR__.'/../../'));
require_once __DIR__.'/../../vendor/autoload.php';
$dotEnv = Dotenv\Dotenv::createUnsafeImmutable(BASE_PATH);// <======== :) look here
$dotEnv->load();
$appName=$_ENV['APP_NAME'];
$appName2=getenv('APP_NAME'];

var_dump($appName) // return "This is my website";
var_dump($appName2) // return "This is my website";

我希望这可以解决您的问题

i hope this resolves your issue

这篇关于PHP getenv始终返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆