Переменная среда php путь

putenv

Добавляет assignment в переменные окружения сервера. Переменная будет существовать только на время выполнения текущего запроса. По его завершении переменная вернётся в изначальное состояние.

Список параметров

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Установка значения переменной среды

Смотрите также

  • getenv() — Получает значение одной или всех переменных окружения
  • apache_setenv() — Устанавливает переменную subprocess_env Apache

User Contributed Notes 8 notes

putenv/getenv, $_ENV, and phpinfo(INFO_ENVIRONMENT) are three completely distinct environment stores. doing putenv(«x=y») does not affect $_ENV; but also doing $_ENV[«x»]=»y» likewise does not affect getenv(«x»). And neither affect what is returned in phpinfo().

Assuming the USER environment variable is defined as «dave» before running the following:

print «env is: » . $_ENV [ «USER» ]. «\n» ;
print «(doing: putenv fred)\n» ;
putenv ( «USER=fred» );
print «env is: » . $_ENV [ «USER» ]. «\n» ;
print «getenv is: » . getenv ( «USER» ). «\n» ;
print «(doing: set _env barney)\n» ;
$_ENV [ «USER» ]= «barney» ;
print «getenv is: » . getenv ( «USER» ). «\n» ;
print «env is: » . $_ENV [ «USER» ]. «\n» ;
phpinfo ( INFO_ENVIRONMENT );
?>

Читайте также:  METANIT.COM

prints:

env is: dave
(doing: putenv fred)
env is: dave
getenv is: fred
(doing: set _env barney)
getenv is: fred
env is: barney
phpinfo()

Variable => Value
.
USER => dave
.

The other problem with the code from av01 at bugfix dot cc is that
the behaviour is as per the comments here, not there:
putenv ( ‘MYVAR=’ ); // set MYVAR to an empty value. It is in the environment
putenv ( ‘MYVAR’ ); // unset MYVAR. It is removed from the environment
?>

White spaces are allowed in environment variable names so :

putenv ( ‘U =33’ );
?>

Is not equivalent to

Environment variables are part of the underlying operating system’s
way of doing things, and are used to pass information between a parent
process and its child, as well as to affect the way some internal
functions behave. They should not be regarded as ordinary PHP
variables.

A primary purpose of setting environment variables in a PHP script is
so that they are available to processes invoked by that script using
e.g. the system() function, and it’s unlikely that they would need to
be changed for other reasons.

For example, if a particular system command required a special value
of the environment variable LD_LIBRARY_PATH to execute successfully,
then the following code might be used on a *NIX system:

$saved = getenv ( «LD_LIBRARY_PATH» ); // save old value
$newld = «/extra/library/dir:/another/path/to/lib» ; // extra paths to add
if ( $saved ) < $newld .= ": $saved " ; >// append old paths if any
putenv ( «LD_LIBRARY_PATH= $newld » ); // set new value
system ( «mycommand -with args» ); // do system command;
// mycommand is loaded using
// libs in the new path list
putenv ( «LD_LIBRARY_PATH= $saved » ); // restore old value
?>

It will usually be appropriate to restore the old value after use;
LD_LIBRARY_PATH is a particularly good example of a variable which it
is important to restore immediately, as it is used by internal
functions.

If php.ini configuration allows, the values of environment variables
are made available as PHP global variables on entry to a script, but
these global variables are merely copies and do not track the actual
environment variables once the script is entered. Changing
$REMOTE_ADDR (or even $HTTP_ENV_VARS[«REMOTE_ADDR»]) should not be
expected to affect the actual environment variable; this is why
putenv() is needed.

Finally, do not rely on environment variables maintaining the same
value from one script invocation to the next, especially if you have
used putenv(). The result depends on many factors, such as CGI vs
apache module, and the exact way in which the environment is
manipulated before entering the script.

It’s the putenv() type of environment variables that get passed to a child process executed via exec().

If you need to delete an existing environment variable so the child process does not see it, use:

That is, leave out both the » note» >

Values of variables with dots in their names are not output when using getenv(), but are still present and can be explicitly queried.

(saw this behaviour using PHP 8.2.4)

// dump explicitely ‘foo.bar’
var_dump ( getenv ( ‘foo.bar’ )); # works, value ‘baz’ is shown

Multiple invocations of putenv() work as expected: the real problem was that some of the putenv() invocations in my script contained typographical errors.

I typed, e.g., putenv( «IMAGE_DATABASE note» >

Great examples for the trivial case that most can figure out directly from the manual, but where is the trivially more complex example describing how to set multiple variables? I tried separating with spaces, commas, semicolons, multiple invocations of setenv, all to no avail. Please try to include trivial extensions to the examples.

  • Опции PHP/информационные функции
    • assert_​options
    • assert
    • cli_​get_​process_​title
    • cli_​set_​process_​title
    • dl
    • extension_​loaded
    • gc_​collect_​cycles
    • gc_​disable
    • gc_​enable
    • gc_​enabled
    • gc_​mem_​caches
    • gc_​status
    • get_​cfg_​var
    • get_​current_​user
    • get_​defined_​constants
    • get_​extension_​funcs
    • get_​include_​path
    • get_​included_​files
    • get_​loaded_​extensions
    • get_​required_​files
    • get_​resources
    • getenv
    • getlastmod
    • getmygid
    • getmyinode
    • getmypid
    • getmyuid
    • getopt
    • getrusage
    • ini_​alter
    • ini_​get_​all
    • ini_​get
    • ini_​parse_​quantity
    • ini_​restore
    • ini_​set
    • memory_​get_​peak_​usage
    • memory_​get_​usage
    • memory_​reset_​peak_​usage
    • php_​ini_​loaded_​file
    • php_​ini_​scanned_​files
    • php_​sapi_​name
    • php_​uname
    • phpcredits
    • phpinfo
    • phpversion
    • putenv
    • set_​include_​path
    • set_​time_​limit
    • sys_​get_​temp_​dir
    • version_​compare
    • zend_​thread_​id
    • zend_​version
    • get_​magic_​quotes_​gpc
    • get_​magic_​quotes_​runtime
    • restore_​include_​path

    Источник

    Как добавить путь до PHP в переменную окружения PATH в Windows

    Вполне возможно, что вам не приходилось ранее сталкиваться с PATH и выражениями «переменная окружения», поэтому я кратко поясню, что это такое.

    Переменная PATH содержит список папок, в которых Windows ищет исполнимые файлы.

    В графическом интерфейсе, когда для запуска программ используются ярлыки, значение PATH не очень большое. Но если вы запускаете программу в командной строке, то PATH может пригодиться. Опять же, если вы указываете полный путь до файла, например, C:\Users\Alex\Documents\php.exe, то PATH не используется. Но если, например, вы запускаете программу только по имени файла или просто по имени (без файлового расширения), то запустится ли программа, будет зависеть от содержимого переменной PATH.

    К примеру, я в командной строке пытаюсь запустить файл (без указания полного пути)

    В этом случае операционная система посмотрит все записи PATH (там может быть указано несколько каталогов). Затем в каждом из этих каталогов Windows попытается найти файл php.exe. Если файл найден, то он будет запущен. Если файл не найден, то будет выведено соответствующее сообщение.

    По сути, что-то дописывать в переменную PATH нужно только тем, кто много работает с командной строкой. К примеру, вы программист и размещаете свои программы в папке C:\MyApps и при этом вы часто запускаете свои утилиты командной строки. В этом случае вы можете добавить C:\MyApps в PATH и после этого для запуска программ из этой папки вам уже не нужно будет каждый раз вводить полное имя (например, C:\MyApps\parser.exe), а достаточно будет в командной строке ввести только имя файла:

    Нужно ли в Windows добавлять PHP в переменную окружения

    При установке и настройке PHP в Windows необязательно добавлять в PATH путь до PHP, но это рекомендуется делать.

    Во-первых, вы сможете запускать PHP используя сокращённую запись:

    C:\Server\bin\PHP\php.exe my_script.php

    Во-вторых, ряд расширений (которые включаются в файле php.ini) работают некорректно, если вы не прописали в PATH путь до PHP; в том числе, это касается такого довольно популярного расширения как cURL. По идее — это какой-то баг этих расширений или PHP, но нам самим придётся исправлять ситуацию, поскольку эта проблема существует уже много лет.

    Как добавить PHP в системные переменные среды

    Нажмите кнопку Windows (это которая раньше была кнопкой «Пуск»), начните набирать «Изменение системных переменных среды»

    и откройте соответствующее окно настроек.

    Там нажмите «Переменные среды», откроется:

    В окне «Системные переменные» найдите и кликните на Path, потом нажмите «Изменить»:

    Далее «Создать» и впишите туда «C:\Server\bin\PHP\»:

    Поднимите запись в самый Вверх:

    Закройте все окна с сохранением сделанных изменений.

    Источник

    Как добавить путь до … в переменную PATH

    В различных руководствах и документациях часто встречается пункт «добавьте путь до чего либо в переменную PATH». Что это за переменная и как в нее что-то добавить описано ниже, в этой заметке.

    Что такое переменная PATH и для чего она нужна?

    Если коротко, то PATH это такая переменная, с помощью нее операционная система ищет исполняемые объекты, которые вы пытаетесь вызвать в командной строке.

    Другими словами, PATH позволяет запускать исполняемые файлы, без указания их точного местоположения на диске. Например, после установки Python на Windows, для выполнения скрипта Питона нам достаточно в командной строке набрать:

    Нам не пришлось указывать точного пути до интерпретатора Питона (в моем случае C:\Users\Alex\AppData\Local\Programs\Python\Python37-32\python.exe) как раз из-за установленной переменной PATH.

    соответствующую программу. Этим можно воспользоваться в своих целях двумя способами:

    Как добавить PHP в системные переменные среды?

    Для примера добавим PHP в переменную PATH.

    У меня на компьютере интерпретатор php располагается в каталоге C:\xampp\php72, поэтому чтобы выполнить php скрипт в командной строке, мне нужно ввести:

    Но согласитесь, гораздо удобней так:

    К тому же некоторые программы, например IDE будут автоматически «понимать» где расположен интерпретатор php.

    Итак, чтобы добраться до настроек переменной PATH, нам сначала нужно открыть Панель управления Windows, поскольку Микрософт постоянно меняет ее положение, проще всего найти ее через поиск:

    Далее нужно выбрать Система -> Дополнительные параметры системы.

    Дополнительные параметры системы Windows 10

    В последних версия Windows 10 Дополнительные параметры системы открываются по такому пути:

    Сначала открываете Все параметры -> Система, далее слева внизу выбираете О программе и справа в списке будет нужный пункт Дополнительные параметры системы.

    Дополнительные параметры системы Windows 10

    В открывшемся окне Свойства системы нужно выбрать вкладку Дополнительно и внизу будет кнопка Переменные среды.

    Переменные среды Windows 10

    Выбираем переменную среды Path и нажимаем Изменить. После этого нажимаем кнопку Создать и вводим пусть до папки, где расположен наш интерпретатор PHP, в моем случае C:\xampp\php72.

    Далее везде нажимаем ОК, все, переменная среды для PHP сохранена.

    Теперь, если перезапустить командную строку, можно выполнять php скрипты не указывая полного пусти к интерпретатору.

    Категории

    Свежие записи

    Источник

    $_ENV

    An associative array of variables passed to the current script via the environment method.

    These variables are imported into PHP’s global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell’s documentation for a list of defined environment variables.

    Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor.

    Examples

    Example #1 $_ENV example

    Assuming «bjori» executes this script

    The above example will output something similar to:

    Notes

    Note:

    This is a ‘superglobal’, or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

    See Also

    User Contributed Notes 2 notes

    If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes «E» in the string.

    Please note that writing to $_ENV does not actually set an environment variable, i.e. the variable will not propagate to any child processes you launch (except forked script processes, in which case it’s just a variable in the script’s memory). To set real environment variables, you must use putenv().

    Basically, setting a variable in $_ENV does not have any meaning besides setting or overriding a script-wide global variable. Thus, one should never modify $_ENV except for testing purposes (and then be careful to use putenv() too, if appropriate).

    PHP will not trigger any kind of error or notice when writing to $_ENV.

    Источник

Оцените статью