PHP.mk документација

getenv

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.getenv.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.getenv.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
getenv

Референца за `function.getenv.php` со подобрена типографија и навигација.

function.getenv.php

getenv

(PHP 4, PHP 5, PHP 7, PHP 8)

getenvЈа добива вредноста на една или сите променливи на околината

= NULL

getenv(?string $name = null, bool $local_only = false): string|array|false

Ја добива вредноста на една или сите променливи на околината.

Можете да видите листа на сите променливи на околината со користење phpinfo(). Многу од овие променливи се наведени во » RFC 3875, поточно делот 4.1, "Request Meta-Variables".

Параметри

name

Името на променливата како string or null.

local_only

Кога е поставено на true, се враќаат само локални променливи на околината, поставени од оперативниот систем или putenv. Има ефект само кога name е string.

Вратени вредности

Враќа вредност на променливата на околината name, или false ако променливата на околината name не постои. Ако name is null, сите променливи на околината се враќаат како асоцијативни array.

Дневник на промени

Верзија = NULL
8.0.0 На name сега е null.
7.1.0 На name сега може да се изостави за да се добие асоцијативна array на сите променливи на околината.
7.0.9 На local_only параметарот е додаден.

Примери

Пример #1 getenv() Пример

<?php
// Example use of getenv()
$ip = getenv('REMOTE_ADDR');

// Or simply use a Superglobal ($_SERVER or $_ENV)
$ip = $_SERVER['REMOTE_ADDR'];

// Safely get the value of an environment variable, ignoring whether
// or not it was set by a SAPI or has been changed with putenv
$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')
?>

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Ако PHP работи во SAPI како Fast CGI, оваа функција секогаш ќе ја врати вредноста на променливата на околината поставена од SAPI, дури и ако putenv() е користено за поставување локална променлива на околината со исто име. Користете го local_only параметарот за враќање на вредноста на локално поставените променливи на околината.

Види Исто така

Белешки од корисници за да означиме кој било валиден PHP израз.

Анонимен
пред 7 години
Contrary to what eng.mrkto.com said, getenv() isn't always case-insensitive. On Linux it is not:

<?php
var_dump(getenv('path')); // bool(false)
var_dump(getenv('Path')); // bool(false)
var_dump(getenv('PATH')); // string(13) "/usr/bin:/bin"
yw()beeznest!com
пред 9 години
As noted on httpoxy.org, getenv() can confuse you in having you believe that all variables come from a "safe" environment (not all of them do).

In particular, $_SERVER['HTTP_PROXY'] (or its equivalent getenv('HTTP_PROXY')) can be manually set in the HTTP request header, so it should not be considered safe in a CGI environment.

In short, try to avoid using getenv('HTTP_PROXY') without properly filtering it.
php на keith tyler точка com
пред 14 години
All of the notes and examples so far have been strictly CGI.
It should not be understated the usefulness of getenv()/putenv() in CLI as well.

You can pass a number of variables to a CLI script via environment variables, either in Unix/Linux bash/sh with the "VAR='foo'; export $VAR" paradigm, or in Windows with the "set VAR='foo'" paradigm. (Csh users, you're on your own!) getenv("VAR") will retrieve that value from the environment.

We have a system by which we include a file full of putenv() statements storing configuration values that can apply to many different CLI PHP programs. But if we want to override these values, we can use the shell's (or calling application, such as ant) environment variable setting method to do so.

This saves us from having to manage an unmanageable amount of one-off configuration changes per execution via command line arguments; instead we just set the appropriate env var first.
eng.mrkto.com
пред 15 години
This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER['Path'] is like you see Capitalized, not 'PATH' as you expected.
So just: <?php getenv('path') ?>
jcastromail на yahoo точка es
пред 5 години
I did a benchmark about env.

constants : 
0.00067687034606934 ms
getenv : 
0.056761026382446 ms

(less is better)

https://github.com/eftec/php-benchmarks#define--const--env

And, in Windows at leat, reading the env value is considerably slow (in comparison with a constant), so PHP doesn't cache the information and asks to the OS the env value per call.

So, if you are calling once per request, then there is not a problem. However, if you are calling it many times per request, then it could affects the performance.
kyong
пред 22 години
As you know, getenv('DOCUMENT_ROOT') is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn't work without modified php.ini
file. So I add "export DOCUMENT_ROOT=~" in my .bash_profile.
Анонимен
пред 6 години
It is worth noting that since getenv('MY_VARIABLE') will return false when the variable given is not set, there is no direct way to distinguish between a variable that is unset and one that is explicitly set to the value bool(false) when using getenv().  
This makes it somewhat tricky to have boolean environment variables default to true if unset, which you can work around either by using "falsy" values such as 0 with the strict comparison operators or by using the superglobal arrays and isset().
pritisn на gmail точка com
пред 10 години
for quick check of getenv() adding a new env variable -
if you add a new env variable, make sure not only apache but xampp is also restarted.
Otherwise getenv() will return false for the newly added env variable.
sam на sambarrow точка com
пред 18 години
SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.
hello на jabran точка me
пред 10 години
Beware that when using this function with PHP built-in server – i.e. php -S localhost:8000 – it will return boolean FALSE.
larby точка robert на gmail точка com
пред 7 години
From PHP 7.1 => getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.

Source: http://php.net/manual/en/migration71.changed-functions.php
chuck точка reeves на gmail точка com
пред 15 години
When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through.  PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.