PHP의 getenv()와 $_ENV의 비교
와의 차이는 무엇입니까?getenv()그리고.$_ENV?
둘 중 어느 쪽을 사용하는가에 대한 단점이 있습니까?
나는 가끔 알아차렸다.getenv()필요한 것을 얻을 수 있는 반면$_ENV하지 않는다(예:HOME).
getenv에 관한 php 매뉴얼에 따르면, 이 문서들은 정확히 동일합니다.단,getenv는 대소문자를 구분하지 않는 파일 시스템(Windows 등)에서 실행할 때 대소문자를 구분하지 않는 방식으로 변수를 검색합니다.Linux 호스트에서도 대소문자를 구분하여 작동합니다.대부분의 경우 문제가 되지 않습니다만, 설명서의 코멘트 중 하나는 다음과 같습니다.
예를 들어 Windows의 $_SERVER['Path']는 예상대로 'PATH'가 아니라 첫 글자가 대문자로 표시됩니다.
그 때문에, 저는 아마 이 제품을 사용하는 것을 선택했을 것입니다.getenv검색하려는 환경 변수의 케이스에 대해 확실하지 않은 경우 교차 플랫폼 동작을 개선합니다.
이 답변에서 Steve Clay의 코멘트는 또 다른 차이점을 강조하고 있습니다.
추가된
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
의 소스 코드를 확인하다getenv이는 PHP가 환경변수를 가져올 수 있는 세 가지 방법이 있기 때문입니다.
- 경유
sapi_getenv(예를 들어 Apache에서 환경변수를 가져오는 경우) - Windows 의 경우, 에서
GetEnvironmentVariableA. - Windows 이외의 경우
getenv제공되는 기능libc.
내가 알기로는 대소문자를 구분하지 않는 방식으로 동작하는 것은 Windows 환경변수 API가 그렇게 동작하기 때문에 Windows에서만 동작합니다.Linux, BSD, Mac 등을 사용하는 경우getenv대소문자를 구분합니다.
마리오가 말했듯이$_ENV의 설정이 다르기 때문에, 반드시 입력되는 것은 아닙니다.variables_order그러니 피하는 것이 가장 좋다.$_ENV서버 구성을 제어하지 않는 경우.
따라서 가장 휴대성이 높은 PHP 코드의 경우:
- 사용하다
getenv. - 환경 변수 이름에 올바른 대소문자를 사용하십시오.
또한 일반적으로는 비어 있습니다.E리스트 되어 있습니다.대부분의 설정에서는 이 설정만 입력되어 있을 가능성이 있습니다.$_ENV는 CLI 전용입니다.
한편, 환경에 직접 액세스 합니다.
(대소문자의 애매성에 대해서는, 보다 간단하게 채용할 수 있습니다).
getenv()때때로 이상한 PHP 버그를 피하기 위해 유용합니다.$_SERVER ★★★★★★★★★★★★★★★★★」$_ENV되지 않았습니다.auto_globals_jit이 네이블이 되어 있습니다(_SERVER 변수와 _ENV 변수를 처음 사용할 때 작성).그때부터 사용하기 시작했어요.
PHP 문서에서 가져온 내용:
합니다(
$_SERVER,$_ENV$검색하기 는 대소문자를 구분하지 않고 $varname 키를 검색하기 때문입니다.를 들면, Windows 의 .$_SERVER['Path']'대문자화'가 '대문자화PATH예상하신 대로입니다.<?php getenv('path') ?>
getenv()는 테스트 목적으로 과부하가 될 수 있기 때문에 더 나은 선택이라고 덧붙입니다.$_SERVARE 또는 $_ENV 변수를 덮어쓰면 테스트 프레임워크 및 기타 라이브러리가 방해될 수 있으며, 궁극적으로 안전하게 수행하기 위해 더 많은 작업이 필요합니다.
사용방법의 잘알 수 만, 는 PHP 사용을 것을 합니다.getenv
https://github.com/vlucas/phpdotenv
getenv() 및 putenv()의 사용은 스레드 세이프가 아니기 때문에 권장되지 않습니다.
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);
}
}
?>
언급URL : https://stackoverflow.com/questions/8798294/getenv-vs-env-in-php
'source' 카테고리의 다른 글
| HTML 속성과 속성의 차이점은 무엇입니까? (0) | 2023.01.29 |
|---|---|
| (Nuxt.js/Vue.js) 새로 고침 후 Vuex 저장소에서 액시오스 인증 토큰 설정 리셋 (0) | 2023.01.29 |
| JavaScript:Alert()를 덮어씁니다. (0) | 2023.01.29 |
| Qlik처럼 판다 데이터 프레임의 열에 고유한 값을 세는 것? (0) | 2023.01.29 |
| PHP: 배열에서 두 날짜 사이의 모든 날짜 반환 (0) | 2023.01.29 |