Windows 10 переменные среды php

Today I will explain how to add your PHP runtime directory to your Windows 10 PATH environment variable.
This will give you global access to php.exe from any command prompt.

Please note that you must reopen your command prompt windows (if you had any open prior to the update).

Command prompt loads the PATH environment variable when it is first open.

Target audience

  • Windows 10 users
  • PHP developers that want PHP to be globally accessible from any command prompt (ex.: php.exe for “linting” or to start a dev. server)

Note that you are not limited to PHP, this can be any directory containing any program — ex.: npm

Copy shortcut: ctrl+C
Paste shortcut: ctrl+V

  1. Find your PHP installation directory and copy it somewhere (your clipboard is a good place)
    • For MAMP users it will be something like C:\MAMP\bin\php\php5.6.21 (the PHP version may vary).
  2. Right-click on the “Start menu”
  3. Click “System”
  4. Click “Advanced system settings”
  5. Click “Environment Variables…”
    win-path-03

  6. Select the “Path” variable (in your user or in the system list)
  7. Click “Edit…”
    win-path-04

  8. Click “New”
  9. Paste your PHP path
    win-path-05

  10. Click OK
  11. Click OK
  12. Click OK
  13. Close your “system window”

And voilà!

How to test if it worked out

  1. Open a command prompt
    1. Right-click on the start menu
    2. Click “Command Prompt” or “Command Prompt (admin)”
  2. In the command prompt, type php -?

If it displays PHP help then it worked!





Comments

How to Set Environment Variable in PHP

This tutorial is an illustrated step-by-step guide on setting up an environment variable for PHP using WAMP on your Windows system. This allows you to use PHP from the command line.

Steps on How to Set the Environment Variable for PHP in Windows

With that said, the following are the steps to set up an environment variable for PHP.

  • Initial setup
  • Launch system settings
  • Launch Advanced system settings
  • Launch the Environment Variables dialog window
  • Create a new User variable
  • Test PHP from the command line

Initial Setup to Set the Environment Variable for PHP in Windows

To follow this tutorial, ensure you have WAMP installed on your system in your C:\ drive. Preferably, the installation folder for WAMP should be c:\wamp64 or c:\wamp32, depending on your system architecture and the version of WAMP you have installed.

Launch System Settings to Set the Environment Variable for PHP in Windows

You can launch the system settings from the Control Panel or via a shortcut from the Run dialog box; we’ll go with the latter option.

Press the Windows+R key simultaneously on your keyboard; this should bring up the Run dialog box, then type control system and hit Enter or click the OK button.

Launch Advanced System Settings to Set the Environment Variable for PHP in Windows

If you are using an earlier version of Windows, you’ll find the Advanced system settings link on the left side of the System Settings window. However, if you are using a modern version of Windows, it will be on the right side.

Clicking on the Advanced system settings link pops up a dialog window.

System Settings in Windows 10

Launch the Environment Variables Dialog Window to Set the Environment Variable for PHP in Windows

In the Advanced system settings dialog window, you’ll find a button close to the bottom of the dialog window. Click on the button that reads Environment Variables, as shown in the image below.

When you click on the button, you are presented with another dialog window to manage User variables and System variables in your system.

System Variables dialog box in Windows 10

Create a New User Variable to Set the Environment Variable for PHP in Windows

The dialog window for the Environment Variables has two sections; the first section is for setting the User variables, while the second section is for the System variables. Our interest lies in the first section.

Click on Path in the first section, then press the New button. Another dialog window pops up to create a New User Variable.

Environment Variables Dialog window in Windows 10

Type Path and the variable value in the variable name, click on the button that reads Browse Directory and navigate to the PHP directory in your WAMP installation.

New User Variable dialog window in Windows 10

If you installed the latest version of WAMP, you could have multiple versions of PHP installed. If that is the case, navigate to the folder of your preferred version of PHP and click the OK button.

The window to create a New User Variable has the variable name, Path and your PHP installation directory. With that, click the OK button to save, and you are set to use PHP from the command line.

New User Variable with filled data of PHP installation directory

Test PHP From the Command Line in Windows

Launch the command line and type php -v; this will display the version you’ve set in the system Environment Variables. If you get the PHP version, that means you can use PHP from the command line.

Checking PHP version via the command line

You can also check the PHP installation information, as shown in the image below.

Checking PHP installation information via the command line

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

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

Шаг 1. Заходим в раздел Downloads официального сайта и скачиваем архив с версией PHP для Windows.

Раздел загрузок официального сайта PHP, в нем мы выбираем Windows downloads, т.е. версию php для операционной системы Windows

Загружаем самую свежую версию — на момент написания статьи это PHP 8.3 (8.3.13)

Шаг 2. Создаем папку в любом удобном месте и распаковываем в неё архив.

Папку с файлами PHP можно создать в любом месте, но в конкретном случае я создал папку php-8 на диске "С" в Program Files

В конкретном случае я создал папку php-8 на диске «С» в Program Files и в нее распаковал загруженный архив

Шаг 3. Копируем путь к папке с PHP.

С нажатой клавишей Shift щелкаем по папке с PHP правой клавишей мыши и в контекстном меню выбираем команду «Копировать как путь»

Шаг 4. Нажимаем сочетание клавиш Win + R для открытия окна «Выполнить», вводим sysdm.cpl и жмем Enter.

Шаг 5. В открывшемся окне «Свойства системы» переходим на вкладку «Дополнительно» и нажимаем на кнопку «Переменные среды…»

Шаг 6. В окне «Переменные среды» в разделе «Системные переменные» выбираем Path и нажимаем кнопку «Изменить…»

Шаг 7. В окне «Изменить переменную среды» нажимаем кнопку «Создать», вставляем путь к папке, удаляем кавычки и жмем ОК.

Проверка версии PHP и возможная ошибка

После установки PHP следует проверить, все ли корректно установилось и готово к работе. Для этого в любом терминале можно набрать команду php -v.

Командную строку можно быстро найти поиском, набрав cmd

При проверке версии PHP появилось предупреждение:

PHP Warning: ‘C:\Windows\SYSTEM32\VCRUNTIME140.dll’ 14.0 is not compatible with this PHP build linked with 14.29 in Unknown on line 0

Чтобы решить проблему, я загрузил и установил последнюю версию Microsoft Visual C++, ссылка на которую доступна на официальном сайте Microsoft.

Я загрузил версию под 64-разрядную ОС

После перезагрузки компьютера предупреждение исчезло.

В терминале отобразилось, что на компьютере установлена и готова к работе версия PHP 8.3.13. Теперь можно писать программы на языке PHP.

На компьютере установлена и готова к работе версия PHP 8.3.13

После успешной установки PHP можно написать первую классическую программу, которая выводит сообщение «Hello World!».

If you’re using XAMPP on your Windows 10 machine, and would like to add the php command so that it’s usable in command prompt, you’re in the right place.

Start by typing in Environment Variables in your Search and click on the Edit the system environment variables result.

In the System Properties window click Environment Variables. Make sure that you’re on the Advanced tab.

Scroll down to the Path variable and click Edit.

Click on the Browse button.

Navigate to C:/xampp/php and click OK.

You will now see the path to php inside the window. Click OK to exit.

Restart your Command Prompt window if it’s open and type in:

php -v

You should see the PHP version being displayed.

You can now use php from CMD.

Запуск PHP в командной строке системы Windows

Раздел содержит примечания и подсказки, которые касаются запуска PHP
из командной строки Windows.

Замечание:

Сначала прочитайте пошаговое
руководство по установке!

PHP запускают из командной строки без внесения каких бы то ни было
изменений в Windows.

C:\php\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

Но есть несколько шагов, которые упрощают запуск PHP из командной строки.
Отдельные шаги уже выполнили, но они повторяются
здесь, чтобы объяснить последовательность действий.

    Замечание:

    Переменные окружения PATH и PATHEXT
    важные переменные, которые появились в Windows в самом начале и которые
    нельзя перезаписывать, а только добавлять для них значения.

  • Добавьте расположение исполняемого файла PHP — php.exe,
    php-win.exe или php-cli.exe,
    в зависимости от версии PHP и предпочтений отображения — в переменную
    окружения PATH. Подробнее о добавлении каталога PHP
    в переменную окружения PATH рассказывает
    запись часто
    задаваемых вопросов.

  • Добавьте расширение .PHP к переменной окружения
    PATHEXT. Это делают одновременно с изменением
    переменной окружения PATH. Выполните те же действия,
    что и в ЧАВО, но измените
    переменную окружения PATHEXT, а не PATH.

    Замечание:

    Позиция, в которую помещают расширение .PHP, будет определять,
    какой скрипт или программа выполнится при совпадении имён файлов.
    Например, расположение расширения .PHP перед расширением
    .BAT запустит скрипт, а не пакетный файл, если каталог
    содержит пакетный файл с тем же названием.

  • Настройте ассоциацию расширения .PHP с типом файла
    путём запуска следующей команды:

  • Настройте ассоциацию типа файла phpfile с исполняемым файлом PHP,
    который соответствует этому типу файла, путём запуска следующей команды:

    ftype phpfile="C:\php\php.exe" -f "%1" -- %~2
    

Эти шаги настроят запуск PHP-скриптов из любого каталога
без ввода исполняемого PHP-файла или расширения
.PHP, а параметры передадутся скрипту для обработки.

Следующий пример приводит отдельные изменения в реестре,
которые вносят вручную.

Пример #1 Пример изменений в реестре

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\php\\php-win.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\php\\php.exe\" -f \"%1\" -- %~2"

С этими изменениями эту же команду получится записать вот так:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3

или, если путь "C:\PHP Scripts" записали в переменную
окружения PATH:

Замечание:

При такой технике запуска возникает небольшая проблема
с запуском PHP-скриптов в качестве фильтра командной строки,
как в примере ниже:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3

или

dir | script -arg1 -arg2 -arg3

Иногда скрипт просто зависает и ничего не выводит.
В реестр вносят ещё одно изменение, чтобы это заработало.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001

Дополнительную информацию по этой проблеме даёт » 
статья базы знаний Microsoft: 321788.
В Windows 10 этот параметр изменили на противоположный, и стандартная
установка Windows 10 поддерживает унаследованные дескрипторы консоли. Это » 
сообщение на форуме Microsoft даёт объяснение.

Нашли ошибку?

pimroes at gmail dot com

14 years ago

Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.

rudigerw at hotmail dot com

9 years ago

On Windows 10 starting php by only typing the script name in an elevated command prompt pops up a dialog to choose an app.
It turns out Windows does that when the program associated with phpfiles through ftype cannot be executed. In this case this happens because it is trying to run php.exe in non-admin mode, even when launched from an elevated command prompt. To fix this, locate your php.exe, right-click, "Properties", "Compatibility", under Settings check "Run this program as an administrator; then also click "Change settings for all users".

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Приложение canon camera connect для windows
  • Не устанавливается lenovo energy management windows 10
  • Приложение камера не работает на windows 10
  • Как открыть средство устранения неполадок windows 10
  • Почему не работает микрофон после переустановки windows 10