установка php на windows 10 iis
Установка php на windows 10 iis
I’ve always liked PHP for creating dynamic Web pages. I find PHP to be much simpler than ASP.NET for some kinds of Web sites.
However, installing PHP on a Windows machine has always been kind of a pain in the patooty. It is possible install PHP using the Microsoft Web Platform Installer, but I prefer to manually install PHP because if something goes wrong using the Web Installer, it’s very, very difficult to fix, but errors in a manual install are easier to track down.
There are five basic steps to install PHP on a Windows 10 machine:
1. Enable (if necessary) IIS on the machine, and IIS-CGI on the machine.
2. Download and extract PHP to C:\PHP
3. Configure the php.ini configuration file
4. Configure IIS to handle PHP page requests
5. Test everything
So, here we go. My instructions are highly abbreviated and are intended for someone who has a medium amount of familiarity with Windows and IIS.
Control Panel | Programs | Turn Windows features on or off
Check Internet Information Services
Check IIS | World Wide Web Services | Application Development Features | CGI
OK
2. Install the NTS (non-thread safe) 64-bit version of PHP
Download and save onto the machine:
Extract all the contents of the zip file to C:\PHP
Now edit the System PATH variable so IIS knows where the PHP executables are:
3. Configure the php.ini file. This is the part you’d never figure out without some help.
Make a copy of file C:\PHP\php.ini-development and save it as C:\PHP\php.ini
Edit file php.ini by finding the following entries, uncomment them, and change values to:
1. fastcgi.impersonate = 1
2. cgi.fix_pathinfo = 0
3. cgi.force_redirect = 0
4. open_basedir = “C:\inetpub\wwwroot”
5. extension_dir = “ext”
6. error_log=”php_errors.log”
7. uncomment the 24 Windows Extensions entries:
extension=php_bz2.dll
extension=php_curl.dll
extension=php_fileinfo.dll
extension=php_ftp.dll
extension=php_gd2.dll
extension=php_gettext.dll
extension=php_gmp.dll
extension=php_intl.dll
extension=php_imap.dll
extension=php_interbase.dll
extension=php_ldap.dll
extension=php_mbstring.dll
extension=php_exif.dll
extension=php_mysqli.dll
extension=php_oci8_12c.dll
extension=php_openssl.dll
extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll
extension=php_pgsql.dll
extension=php_shmop.dll
Save the edited php.ini file.
4. Configure IIS to work with PHP
Run | inetmgr
Handler Mappings | Add Module Mapping
Request path: *.php
Module: FastCgiModule (from the dropdown)
Executable (optional): C:\PHP\php-cgi.exe
Name: FastCGI
5. Test the installation and configuration
Launch Notepad with Administrative privleges. Create a file test.php and save it at C:\inetpub\wwwroot. The contents are (I use an image because my blog software would choke on HTML text):
Now launch a browser and navigate to
And hopefully it works. There’s a LOT that can go wrong, but by Googling one error at a time you should eventually be able to get a Windows 10 machine with IIS to serve up PHP Web pages.
Установка PHP 7.3.1 на IIS 10
Расскажу вам о наиболее оптимальном способе установки PHP на IIS. Ставить будем PHP 7.3.1 на IIS 10. IIS крутится на сервере с Windows Server 2016. Раньше я устанавливал PHP руками, помните, что для Windows нужно выбирать PHP NTS версию.
If you are using PHP as FastCGI with IIS you should use the Non-Thread Safe (NTS) versions of PHP.
Однако, на этот раз я решил последовать совету с официального сайта. На php.net немного коряво написано:
Если вы хотите настроить PHP используя в качестве веб-сервера IIS, то проще всего это сделать используя
Microsoft Web Platform Installer (WebPI).
Нажимаем зелёную кнопку Install this extension и качаем инсталлятор.
Открывается мастер установки WebPI.
Установка завершена, это было несложно. Finish.
Находим в установленных программах Web Platform Installer и запускаем.
Ждём. Открывается окошко.
Обещают установить три модуля:
Полетела установка. Но взлетела не очень высоко.
We’re sorry. The following product have failed to install.
PHP Manager for IIS не поставился, ай-ай-ай, как печально. Зато поставилось куча всего другого, что нам поставить не обещали:
Ладно, если что, лишний PHP удалю потом. Давайте решим вопрос с PHP Manager for IIS. Гуглим ссылочку:
Нажимаем Download this extension.
OK. Запускается мастер установки.
Принимаем лицензионное соглашение, Next.
В IIS появляется новая оснастка под названием PHP Manager.
Внутри не сложно, разобраться можно.
Для каждого сайта можно выбирать свою PHP версию, регистрировать новые, управлять расширениями и т.д.
Установка и настройка компоненты PHP для веб-сервера IIS
Для работы с веб-проектами на базе популярных CMS (англ. Content Management System — система управления содержимым), таких как WordPress, Drupal, Joomla и др. необходим компонент, который бы обрабатывал скрипты PHP и преобразовывал бы их в код HTML, понятный браузеру. В данной статье рассмотрим 2 способа установки компоненты PHP на входящий в поставку Windows веб-сервер IIS (Internet Information Services) с помощью программы «Установщик веб-платформы» от компании Mocrosoft и вручную, с помощью официального инсталлятора.
0. Оглавление
1. Установка и настройка веб-сервера IIS
Прежде всего, у вас должен быть установлен веб-сервер IIS. Об установке IIS можно прочитать в статьях:
Кроме того, в процессе установки помимо компонент по умолчанию обязательно должна быть установлена компонента FastCGI. Если же веб-сервер IIS уже установлен, но данная компонента не была выбрана, то это можно сделать и позже. Рассмотрим процесс установки компоненты FastCGI в Winows 8/8.1. Чтобы активировать FastCGI, проходим тот же путь, что и для активации IIS. Кстати, в Windows 8.1 нужный нам раздел панели управления «Программы и компоненты» удобно вынесен в контекстное меню кнопки «Пуск».
В открывшемся окне раздела кликаем «Включение и отключение компонентов Windows».
Раскрываем список «Службы IIS», в нём – «Службы Интернета», далее – «Компоненты разработки приложений». И уже в этом списке ставим галочку возле «CGI». Далее жмём «ОК» и дожидаемся, пока система настроит и применит изменения.
Далее рассмотрим 2 способа установки компоненты PHP на веб-сервер IIS:
2. Установка компоненты PHP с помощью программы «Установщик веб-платформы»
Установщик веб-платформы предоставляет собой небольшую программу, предоставляющую доступ к быстрой установке и настройке всего спектра продуктов, которые могут понадобиться для разработки или развертывания веб-сайтов и веб-приложений на базе платформы Windows. Скачать установщик веб-платформы можно на официальном сайте программы.
После скачивания запускаем инсталлятор и дожидаемся окончания установки. После того, как процесс установки будет завершен, мы попадем в главное окно программы, где можно увидеть огромное количество программ, компонент, сборок и пр. существующих для разработки веб-сайтов и веб-приложений. Необходимая нам компонента PHP также присутствует в данном списке. Найти ее проще всего вбив соответствующий запрос в поле поиска, расположенное в верхнем правом углу окна программы. Затем необходимо нажать кнопку «Добавить» в строке с компонентой требуемой версии (на момент написания статьи, актуальной была версия 5.63)
Данная компонента будет добавлена в список устанавливаемых элементов. Нажимаем «Установить» для установки приложений из этого списка.
Запустится мастер установки, принимаем условия лицензионного соглашения нажав кнопку «Принимаю».
И дожидаемся окончания установки, нажав «Готово» когда мастер закончит работу.
На этом в общем то и все. Компонента PHP успешно установлена. Аналогичным образом можно также добавить компоненту «Диспетчер PHP для IIS» с помощью которой можно будет настраивать компоненты PHP прямо из «Диспетчера служб IIS».
3. Установка компоненты PHP с помощью официального инсталлятора
Теперь рассмотрим процесс установки компоненты PHP вручную, т. е. с помощью инсталлятора. Дистрибутив PHP можно скачать с официального сайта. В нашем случае скачиваем инсталлятор PHP.
Запускаем инсталлятор PHP и в окне мастера установки жмём «Next».
Соглашаемся с лицензионными условиями. Жмём «Next».
Соглашаемся с путём установки, если нет необходимости его менять. Жмём «Next».
В следующем окне выбираем режим «IIS FastCGI», если текущая операционная система — Windows Server. Если работа происходит в Windows 7, 8, 8.1, выбираем режим «Other CGI». И жмём «Next».
Затем, ничего не меняя, жмём «Next».
Следующий шаг – запуск самой инсталляции. Жмём «Install».
По завершению инсталляции жмём «Finish».
В довесок к самому PHP также установим плагин для его управления в «Диспетчере служб IIS». Плагин PHP Manager for IIS, в соответствии с разрядностью операционной системы, скачиваем с официального сайта.
Запускаем установку плагина. Если на компьютере не установлена программная платформа NET Framework, инсталлятор плагина предложит отправиться на официальный сайт для скачивания её дистрибутива. И только после установки NET Framework и перезагрузки компьютера плагин PHP Manager for IIS захочет устанавливаться без каких-либо проблем. Жмём «Next».
Соглашаемся с лицензионными условиями и жмём снова «Next».
По завершению установки плагина закрываем окно установщика.
Запускаем «Диспетчер служб IIS». Если все действия осуществлены корректно, в «Диспетчере служб IIS» увидим появившийся раздел «Администратор PHP». Заходим сюда двойным щелчком.
Для дальнейшем работы потребуется зарегистрировать компоненту PHP – увидим активной ссылку регистрации новой версии PHP. Жмём её.
В появившемся окошке указываем путь к запрашиваемому исполняемому файлу и нажимаем «ОК».
Это завершающий этап настройки PHP.
Смотрите также:
IIS (Internet Information Services) – один из немногих штатных инструментов Windows, которым можно пользоваться, не ища более приемлемых альтернатив от других разработчиков. Веб-сервер IIS с поддержкой языка PHP можно использовать…
Раннее я уже писал об установке сервера хранилища конфигураций в системе «1С:Предприятия» 8. В данной статье рассмотрим процесс публикации сервера хранилища конфигураций на веб-сервере IIS для возможности доступа к хранилищам, обслуживаемым…
Веб-сервер представляет собой некоторую программу (службу), принимающую HTTP-запросы от клиентов, обычно от веб-браузеров, обрабатывающую данные запросы и выдающую им ответ, как правило, вместе с HTLM-страницей (сайтом), изображением, файлом, медиа-потоком или другими данными. Ниже подробно рассмотрим…
Install and Configure PHP
The fastest and easiest way to install PHP on Internet Information Services (IIS) is by using the MicrosoftВ® Web Platform Installer (Web PI). Web PI completely automates setting up IIS, FastCGI, and the latest version of PHP from the php.net Web site. With Web PI, you can navigate to the «Web Platform» tab and select «PHP» under «Framework and Runtimes» customize link. Alternately, use the instructions that follow as guidance for installing PHP with WindowsВ® Installer or using a compressed (Zip) file installation.
There are two builds for each PHP version: one is thread-safe, and one is not (referred to as the non-thread-safe [NTS] version). The thread-safe version is designed for environments where the Web server core can keep the PHP engine in memory, running multiple treads of execution for different Web requests simultaneously. The architecture of IIS and the FastCGI extension provide an isolation model that keeps requests separate, removing the need for a thread-safe version. The NTS version does not have any of the code that allows PHP to manage multiple threads. As a result, there is a performance improvement on IIS when using the NTS version when compared to the tread-safe version because the NTS version avoids unnecessary thread-safety checks (FastCGI ensures a single-threaded execution environment).
Install PHP
There are two main ways to install PHP on a WindowsВ®-based computer: download the Windows Installer or use the Windows Zip file from the PHP Web site. Either method will get PHP working, but both have some extra steps that are needed to make PHP work well.
Windows Installer
The Windows Installer version can get a complete PHP environment up and running, but the installation of extensions can be confusing. By default, no extensions are installed, and this can adversely affect the usefulness of the PHP installation. Alternately, all of the extensions can be installed; this results in an unstable system because some of the extensions can conflict with others. It is generally easier to use the Zip file installation.
Zip File Installation
To use the Zip file installation, follow the instructions in Using FastCGI to Host PHP Applications on IIS 7.0 and Above. The Zip file installation installs many of the extensions that are available for the Windows Installer version; however, none of the extensions are enabled until their entries in the Php.ini file are set up.
Download the latest non-thread-safe Zip file package with binaries of PHP. Under Windows Binaries, click on the most current PHP non-thread-safe Zip package to download the PHP files.
Unpack the files to a directory of your choice (for example, C:\PHP ) on your IIS server.
Rename the Php.ini-recommended to php.ini.
Open the Php.ini file in a text editor, then uncomment and modify settings as follows:
Set fastcgi.impersonate = 1.
FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.
Set cgi.fix_pathinfo = 0
The cgi.fix_pathinfo provides PATH_INFO/PATH_TRANSLATED support for Common Gateway Interface (CGI). Setting this to 1 will cause PHP CGI to fix its paths to conform to the specification.
Set cgi.force_redirect = 0.
Set open_basedir to point to a folder or network path where the content of the Web site(s) is located.
Set extension_dir to point to a location where PHP extensions reside. For PHP 5.2.X, this is typically extension_dir = «./ext».
Set error_log=»C:php_errors.log»
This can help with troubleshooting.
Enable the required PHP extension by un-commenting corresponding lines. More information follows in the section, Extensions.
Figure 1 Windows extensions
Click on Start, Settings, Control Panel, and then double-click on the System icon (using the class view).
Click on the Advanced system settings link in the left column.
From the System Properties window, click on the Advanced tab, and then click on the Environment Variables button at the bottom.
Select the Path variable from the System Variables section, and then click on Edit. Add: c:\php to your system path.
Figure 2: Edit System Variable
Click OK until you have exited the System Properties window.
Start IIS Manager by clicking on Start, Programs, Administrative Tools, and then Internet Information Services (IIS) Manager.
From the IIS Manager, click on the hostname of your server in the Connections panel on the left.
Double-click on the Handler Mappings icon.
Figure 3: Internet Information Services (IIS) Manager
From the Handler Mappings Actions panel, click on Add Module Mapping.
Figure 4: Handler Mappings
Type the following information into the appropriate text boxes, and then click OK.
Figure 5: Add Script Map
Click OK, and then c lick Yes.
In the left panel, click on your server’s hostname, and then double-click on the Default Document icon.
From the Actions panel on the right, click Add.
Enter index.php as the new default document name, and then click OK.
Enter default.php as the new default document name, and then click OK.
In the left panel, click on your server’s hostname.
In the Actions panel on the right, click Restart.
Create a new text document, and save it as c:\inetpub\wwwroot\phpinfo.php with the following content:
Figure 6: PHP information page
Extensions
It is important to determine which extensions are needed by the applications that will be running and then to limit the installed extensions to only those. For a typical open-source application installation, for example, the following extensions are installed:
PHP.INI File Settings
The Php.ini file provides PHP with configuration and environmental information. Below are a number of settings for the Php.ini file that help PHP work better with Windows.
Required Settings
Optional Settings
Enable PHP Session State
In WindowsВ® Explorer, create the session subdirectory in the PHP installation directory.
Right-click the session directory, and select Properties.
In the Security tab, click Edit.
Click Add, and enter IIS_IUSRS for Enter the object names to select.
Click OK.
Select the Modify permission check box, and click OK.
Figure 7: Permissions for session folder
Click OK in the Session Properties window.
Open php.ini in the PHP installation directory, and set the session.save_path setting to the session subdirectory:
Save and close the file.
Click Start, and then select Command Prompt.
Type runas /user:administrator cmd.exe to enable elevated permissions.
Type iisreset at the command prompt, and then press the ENTER key.
Figure 8: IISRESET command
Note that PHP uses file-based session state by default. You can modify a number of additional session settings, including whether cookie or URL sessions should be used, and whether sessions are created on the first request or need to be explicitly created.
Create a folder and rename it phpapp.
Create session.php in the phpapp directory.
Paste the following into it:
Save and close the file.
Figure 9: Using session state
Observe that the counter is 1.
Request http://localhost/phpapp/session.php again, or press F5.
Figure 10: Using session state
Observe that the counter is 2.
This article uses information from «Using FastCGI to Host PHP Applications on IIS 7.0 and Above» by Ruslan Yakushev, published on December 5, 2007.