getenv() vs. $_ENV in PHP



getenv()$_ENV之间有什么区别?

使用两者之间有任何权衡吗?

我注意到有时getenv()会提供我需要的东西,而$_ENV则不会(例如HOME)。

根据关于getenv的php文档,它们完全相同,只是getenv在不区分大小写的文件系统(如Windows)上运行时会以不区分大小字母的方式查找变量。在Linux主机上,它仍然是区分大小写的。大多数时候,这可能无关紧要,但文档上的一条评论解释道:

例如,在Windows$_SERVER["路径"]中,第一个字母大写,而不是您所期望的"路径"。

因此,我可能会选择使用getenv来改进跨平台行为,除非您确定要检索的环境变量的大小写。

Steve Clay在这个答案中的评论突出了另一个区别:

增加了getenv()的优点:访问前无需检查isset/emptygetenv()不会发出通知。

我知道文档中的注释说getenv不区分大小写,但这不是我看到的行为:

> env FOO=bar php -r 'print getenv("FOO") . "n";'
bar
> env FOO=bar php -r 'print getenv("foo") . "n";'
> env foo=bar php -r 'print getenv("foo") . "n";'
bar
> env foo=bar php -r 'print getenv("FOO") . "n";'
> php --version
PHP 5.4.24 (cli) (built: Jan 24 2014 03:51:25)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies

查看getenv函数的源代码,这是因为PHP可以通过三种方式获取环境变量:

  1. 通过sapi_getenv(例如,如果从Apache获取环境变量)
  2. 如果在Windows上,则从GetEnvironmentVariableA开始
  3. 如果在非Windows上,则来自libc提供的getenv功能

据我所知,它以不区分大小写的方式表现的唯一时间是在Windows上,因为Windows环境变量API就是这样表现的。如果您使用的是Linux、BSD、Mac等,那么getenv仍然区分大小写。

正如mario所提到的,由于variables_order的配置不同,$_ENV并不总是被填充的,因此如果不控制服务器配置,最好避免使用$_ENV

因此,对于最可移植的PHP代码:

  1. 使用getenv
  2. 环境变量名称使用正确的大小写

此外,如果variables_order没有列出E,则$_ENV通常为空。在许多设置中,可能只填充了$_SERVER,而$_ENV严格用于CLI。

CCD_ 28直接访问环境。

(关于案例歧义,可以更简单地使用array_change_key_case()。)

我发现getenv()有助于避免一个奇怪的PHP错误,如果启用了auto_globals_jit,有时$_SERVER$_ENV是未定义的(在首次使用时创建_SERVER_ENV变量)。从那时起,我开始使用它。

取自PHP文档:

此函数非常有用(与$_SERVER$_ENV相比),因为它以不区分大小写的方式搜索$varname键。例如,在Windows上,$_SERVER['Path']就像您看到的大写,而不是您预期的"PATH"。所以只是:<?php getenv('path') ?>

我想补充一下,getenv()是一个更好的选择,因为作为一个函数,它可以重载以用于测试目的。而重写$_SERVER或$_ENV变量可能会干扰测试框架和其他库,并最终需要更多的工作来安全地执行。

我认为现有的答案很好地概括了使用上的任何差异,但也值得记住的是,用于加载环境变量的流行PHP库的维护人员建议避免使用getenv

https://github.com/vlucas/phpdotenv

强烈建议使用getenv()和putenv(

$_ENV是一个包含所有环境变量的超全局数组。您可以使用特定环境变量的名称作为$_ENV数组中的键来访问该变量。例如,$_ENV['DB_HOST']将为您提供DB_HOST环境变量的值。

getenv()是一个以环境变量的名称为参数并返回其值的函数。例如,getenv('DB_HOST')将为您提供DB_HOST环境变量的值。

两者的主要区别在于$_ENV是一个超全局数组,这意味着它在PHP代码中始终可用,而getenv()是一个需要显式调用的函数。

读取env并创建

<?php
namespace neoistone;
class ns_env {
    
    
    /**
     * env to array file storage
     *
     * @param $envPath
     */
    public static function envToArray(string $envPath)
    {
        $variables = [];
        $mread = fopen($envPath, "r");
        $content = fread($mread,filesize($envPath));
        fclose($mread);
        $lines = explode("n", $content);
        if($lines) {
            foreach($lines as $line) {
                // If not an empty line then parse line
                if($line !== "") {
                    // Find position of first equals symbol
                    $equalsLocation = strpos($line, '=');
                    // Pull everything to the left of the first equals
                    $key = substr($line, 0, $equalsLocation);
                    // Pull everything to the right from the equals to end of the line
                    $value = substr($line, ($equalsLocation + 1), strlen($line));
                    $variables[$key] = $value;
                } else {
                    $variables[] = "";
                }
            }
        }
        return $variables;
    }
  
    /**
     * Array to .env file storage
     *
     * @param $array
     * @param $envPath
     */
    public static function arrayToEnv(array $array, string $envPath)
    {
        $env = "";
        $position = 0;
        foreach($array as $key => $value) {
            $position++;
            // If value isn't blank, or key isn't numeric meaning not a blank line, then add entry
            if($value !== "" || !is_numeric($key)) {
                // If passed in option is a boolean (true or false) this will normally
                // save as 1 or 0. But we want to keep the value as words.
                if(is_bool($value)) {
                    if($value === true) {
                        $value = "true";
                    } else {
                        $value = "false";
                    }
                }
                // Always convert $key to uppercase
                $env .= strtoupper($key) . "=" . $value;
                // If isn't last item in array add new line to end
                if($position != count($array)) {
                   $env .= "n";
                }
            } else {
                $env .= "n";
            }
        }
        $mwrite = fopen($envPath, "w");
        fwrite($mwrite, $env);
        fclose($mwrite);
    }
    /**
     * Json to .env file storage
     *
     * @param $json
     * @param $envPath
     */
    public static function JsonToEnv(array $json, string $envPath)
    {
        $env = "";
        $position = 0;
        $array = json_decode($json,true);
        foreach($array as $key => $value) {
            $position++;
            // If value isn't blank, or key isn't numeric meaning not a blank line, then add entry
            if($value !== "" || !is_numeric($key)) {
                // If passed in option is a boolean (true or false) this will normally
                // save as 1 or 0. But we want to keep the value as words.
                if(is_bool($value)) {
                    if($value === true) {
                        $value = "true";
                    } else {
                        $value = "false";
                    }
                }
                // Always convert $key to uppercase
                $env .= strtoupper($key) . "=" . $value;
                // If isn't last item in array add new line to end
                if($position != count($array)) {
                   $env .= "n";
                }
            } else {
                $env .= "n";
            }
        }
        $mwrite = fopen($envPath, "w");
        fwrite($mwrite, $env);
        fclose($mwrite);
    }
    /**
     * XML to .env file storage
     *
     * @param $json
     * @param $envPath
     */
    public static function XmlToEnv(array $xml, string $envPath)
    {
        $env = "";
        $position = 0;
        $array = simplexml_load_string($xml);
        foreach($array as $key => $value) {
            $position++;
            // If value isn't blank, or key isn't numeric meaning not a blank line, then add entry
            if($value !== "" || !is_numeric($key)) {
                // If passed in option is a boolean (true or false) this will normally
                // save as 1 or 0. But we want to keep the value as words.
                if(is_bool($value)) {
                    if($value === true) {
                        $value = "true";
                    } else {
                        $value = "false";
                    }
                }
                // Always convert $key to uppercase
                $env .= strtoupper($key) . "=" . $value;
                // If isn't last item in array add new line to end
                if($position != count($array)) {
                   $env .= "n";
                }
            } else {
                $env .= "n";
            }
        }
        $mwrite = fopen($envPath, "w");
        fwrite($mwrite, $env);
        fclose($mwrite);
    }
}
?>

最新更新