getenv()과 의 차이점은 무엇입니까 $_ENV?
둘 중 하나를 사용하는 것 사이의 장단점이 있습니까?
나는 때때로 getenv()내게 필요한 것을 제공하지만 $_ENV그렇지 않은 경우 (예 :)를 발견했습니다 HOME.
getenv()과 의 차이점은 무엇입니까 $_ENV?
둘 중 하나를 사용하는 것 사이의 장단점이 있습니까?
나는 때때로 getenv()내게 필요한 것을 제공하지만 $_ENV그렇지 않은 경우 (예 :)를 발견했습니다 HOME.
답변:
getenv 에 대한 PHP 문서에 따르면 getenv대소 문자를 구분하지 않는 방식으로 변수를 찾는 것을 제외하고는 정확히 동일 합니다. 대부분의 경우 문제가되지는 않지만 문서의 주석 중 하나는 다음과 같이 설명합니다.
예를 들어 Windows에서 $ _SERVER [ 'Path']는 예상대로 'PATH'가 아니라 첫 글자가 대문자로 표시되는 것과 같습니다.
따라서 getenv검색하려는 변수 제목의 대 / 소문자가 확실하지 않으면 사용하기로 선택했을 것입니다 .
getenv()이점 : 액세스하기 전에 확인 isset/ 확인할 필요가 없습니다 empty. getenv()통지를 발행하지 않습니다.
나는 문서의 주석 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
보면 소스 코드 에 대한 getenvPHP 환경 변수를 가져올 수있는 세 가지 방법이 있기 때문에 기능이 있습니다 :
sapi_getenv(예 : Apache에서 환경 변수를 가져 오는 경우)GetEnvironmentVariableA.getenv제공 하는 함수 에서 libc.내가 말할 수있는 한, 대소 문자를 구분하지 않는 방식으로 작동하는 유일한 시간은 Windows 환경 변수 API가 작동하는 방식이기 때문에 Windows에서만 작동합니다. Linux, BSD, Mac 등을 사용하는 getenv경우 여전히 대소 문자를 구분합니다.
에서 언급 한 바와 같이 마리오 , $_ENV때문에 항상 다른 구성으로 채워지지 않습니다 variables_order당신이 피 경우 가장 그래서 $_ENV서버 구성을 제어하지 않는 경우.
따라서 가장 이식성이 높은 PHP 코드의 경우 :
getenv.또한 $_ENV경우 일반적으로 비어 variables_orderdoes't가있다 E나열. 많은 설정에서 만 $_SERVER채워질 가능성이 높으며 $_ENVCLI 사용을위한 것입니다.
반면에 getenv()환경에 직접 액세스합니다.
(대소 문자의 모호성에 관해서는 array_change_key_case().)
내가 발견 getenv()것을 방지하는 데 유용 이상한 PHP 버그 곳 때때로을 $_SERVER하고 $_ENV있는 경우 정의되지 않은 한 auto_globals_jit활성화되었다합니다 (생성 _SERVER 및 _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);
}
}
?>
$_ENV그리고$_SERVER다양한 방법으로 얻은 데이터로 채워집니다.getenv()PHP가 직접 액세스 할 수없는 데이터에 액세스하는 또 다른 방법입니다.variables_order = "G", 때$_SERVER및$_ENV비어있는 경우 에도 작동합니다 . Conor McDermottroe 의 훌륭한 답변을 읽어보십시오 .