- Установка и настройка веб-сервера IIS + PHP + MySQL
- Установка IIS
- Развертывание отдельного сайта
- Hello from PHP site
- Установка PHP
- Настройка сайта на IIS для работы с PHP
- PHP Manager в IIS
- Установка MySQL
- Configuring Step 1: Install IIS and PHP
- 1.1. Install IIS
- To install IIS on Windows Server 2012
- To install IIS on Windows 8
- 1.2. Install PHP by using Web PI
- To install PHP by using Web PI
- 1.3. Download and Install PHP Manually
- To download and install PHP and WinCache
- To test your PHP installation
- 1.4. Add Your PHP Application
- To add a PHP web application
Установка и настройка веб-сервера IIS + PHP + MySQL
Чаще всего, PHP и MySQL устанавливается на серверы с Linux. Однако, при необходимости, можно настроить запуск и обработку PHP скриптов на Windows. Версии последней могут быть разные, например, Server 2008/2012/2016/2019 или не серверные системы, такие как, 7/8/10. Данная инструкция подойдет как для чайника, так и опытного специалиста (в качестве шпаргалки).
Установка IIS
Для установки веб-сервера, открываем Диспетчер серверов — переходим в Управление — Добавить роли и компоненты:
Если откроется окно с приветствием, нажимаем Далее:
При выборе типа установки выбираем Установка ролей или компонентов:
При выборе целевого сервера оставляем локальный сервер (или выбираем удаленный, если установка выполняется из удаленной консоли):
Среди ролей выбираем Веб-сервер (IIS) — во всплывающем окне кликаем по Добавить компоненты:
Также среди ролей в подразделе «Разработка приложений» ставим галочку для установки CGI — этот компонент нам нужен для работы PHP:
При выборе компонентов ничего не меняем — нажимаем Далее:
Откроется окно настройки роли веб-сервера — просто нажимаем Далее:
Выбор служб ролей — нажимаем далее или, при необходимости, выбираем FTP-сервер:
В следующем окне ставим галочку Автоматический перезапуск конечного сервера, если требуется и кликаем по Установить:
Дожидаемся окончания процесса установки.
Сразу после установки IIS запускается автоматически. Но, если что, его можно запустить с помощью команды iisreset:
* если выполнить данную команду без опций, то она перезапустить веб-сервер.
Также мы можем открыть диспетчер служб (команда services.msc) и перезапустить Службу веб-публикаций:
Открываем браузер и вводим адрес http://localhost — должен открыться стартовый портал:
Развертывание отдельного сайта
Мы можем пропустить данный пункт, если хотим использовать сайт по умолчанию. Однако, в данной инструкции мы разберем пример, когда для сайта на PHP будет создана отдельная настройка.
Открываем Диспетчер серверов — кликаем по Средства — Диспетчер служб IIS:
Находим раздел сайты — кликаем правой кнопкой мыши по Добавить веб-сайт. :
Заполняем данные для нового сайта:
- Имя сайта — произвольно имя будущего сайта.
- Физический путь — путь до папки на сервере, где будут расположены файлы сайта.
- Тип — тип соединения (http или https). Для первого запуска обойдемся http. При необходимости, его можно всегда поменять или использовать оба типа одновременно.
- IP-адрес — если на сервере много IP-адресов, то мы можем выбрать конкретный, на котором будет работать сайт.
- Порт — сетевой порт, на котором будет работать сайт. Как правило, это 80 для http или 443 для https.
- Имя узла — доменное имя сайта, при обращении по которому должен открываться создаваемый сайт.
После заходим в каталог с сайтом (в нашем примере, это C:\inetpub\wwwroot\php) и создадим в нем файл index.html со следующим содержимым:
Hello from PHP site
Открываем браузер и переходим на созданный сайт, например, как в нашей инструкции — http://php.dmosk.ru. Мы должны увидеть страницу с написанным нами текстом:
Тестовый сайт создан.
Установка PHP
Для установки php на Windows переходим на страницу загрузки PHP — выбираем нужную нам версию, например, последнюю стабильную и переходим по ссылке для загрузки версии для Windows:
Откроется страница с несколькими версиями пакета — там как мы ставим PHP как FastCGI, нам нужна версия «Non Thread Safe» (не потокобезопасная), так как она будет работать быстрее. И так, скачиваем zip-архив на сервер:
Для установка PHP на Windows достаточно просто распаковать содержимое архива в любой каталог, например, C:\Program Files\PHP:
Делаем копию файла php.ini-production и переименовываем его в php.ini:
Открываем на редактирование данный файл и правим следующее:
open_basedir = C:\inetpub\wwwroot
.
cgi.force_redirect = 0
.
short_open_tag = On
* где open_basedir — директория, в которой будут разрешены PHP-скрипты; cgi.force_redirect — указывает будет ли скрипты обрабатываться при прямом запросе или только при запросе от веб-сервера. В IIS запросы контролируются самим веб-сервером, поэтому опция может оказать обратный эффект; short_open_tag — позволяет использовать короткий вид открывающих тегов для PHP.
Проверяем, что PHP работает. Открываем командную строку Windows — переходим в каталог с установленным PHP:
cd «C:\Program Files\PHP»
Запускаем php с параметром -m:
Мы должны получить список подключенных модулей:
[PHP Modules]
bcmath
calendar
Core
ctype
.
Но если мы получим ошибку, связанную с отсутствием файла VCRUNTIME140.dll:
. необходимо установить Microsoft Visual C++ Redistributable. Переходим на страницу https://www.microsoft.com/ru-RU/download/details.aspx?id=52685 и скачиваем компонент:
После загрузки, устанавливаем его на сервер, после чего, снова пробуем вывести на экран модули php:
Настройка сайта на IIS для работы с PHP
И так, веб-сервер поднят, PHP установлено, сайт работает. Настроим связку IIS + PHP. Открываем панель управления IIS — переходим к созданному сайту и кликаем по Сопоставления обработчиков:
В меню справа кликаем по Добавить сопоставление модуля:
- Путь запроса — путь к файлам, при вызове которых действует сопоставление. В данном примере для всех файлов, заканчивающихся на php.
- Модуль — действующий модуль для обработки запроса.
- Исполняемый файл — файл, который будет выполнять обработку запроса. В данном примере мы выбрали файл из скачанного и распакованного нами архива PHP.
- Имя — произвольное имя для сопоставления.
Нажимаем OK и подтверждаем действие. Сопоставление создано.
Теперь заходим в Документ по умолчанию:
. и добавляем новый документ:
* в данном примете мы указываем, что по умолчанию сервер будет искать файл index.php, если таковой не указан явно в запросе.
Открываем в проводнике папку, в которой находятся файлы сайта (в нашем примере, C:\inetpub\wwwroot\php). Создаем файл index.php с содержимым:
Открываем браузер и снова переходим на наш сайт — мы должны увидеть страницу с информацией о php:
PHP Manager в IIS
Для того, чтобы упростить настройку PHP мы можем установить диспетчер PHP для IIS. Для этого переходим по ссылке https://www.iis.net/downloads/community/category/manage и переходим по ссылке для скачивания стабильной версии php-менеджера:
Выполняем установку на сервере, запустив загруженный файл. Открываем диспетчер управления IIS — мы должны увидеть PHP Manager:
Установка MySQL
MySQL для Windows можно скачать бесплатно. Переходим на страницу https://dev.mysql.com/downloads/mysql/ — выбираем операционную систему Microsoft Windows — кликаем по Go to Download Page:
На следующей странице выбираем для скачивания mysql-installer-community:
В открывшемся окне кликаем по No thanks, just start my download:
Начнется загрузка файла для установки MySQL. Дожидаемся скачивания и запускаем установочный файл — в открывшемся окне выбираем Server only:
В следующем окне кликаем по Execute:
. и дожидаемся установки СУБД:
Откроется окно конфигурации MySQL — нажимаем Next:
Выбираем установку одиночного сервера MySQL:
Оставляем все значения по умолчанию для настроек сети:
Требуем сложные пароли:
Вводим дважды пароль для пользователя root:
* также, на данном этапе мы можем сразу добавить новых пользователей.
Устанавливаем СУБД как сервис и стартуем его:
Настройки готовы для применения — нажимаем Execute:
Дожидаемся применения настроек и кликаем по Next:
Установка завершена — нажимаем Finish.
Сервер баз данных готов к использованию.
По умолчанию, PHP поддерживаем mysql — в этом можно убедиться на странице phpinfo, найдя раздел mysqlnd:
Configuring Step 1: Install IIS and PHP
by Keith Newman and Robert McMurray
In this step of building a PHP website, you install IIS and FastCGI, download and install PHP and the WinCache extension, and upload your PHP application.
When you are done, make sure that IIS and the PHP are installed, and your PHP application has been added to your website. Then go on to Step 2: Configure PHP Settings.
1.1. Install IIS
You can use the Web Platform Installer (Web PI) to install IIS, and applications that run on IIS. Web PI installs the latest versions of available Web Platform offerings with just a few simple clicks. Using Web PI, you can download and install any new tools or updates, including PHP. To learn more about the Web PI, see Learn more and install the Web PI.
If you do not use Web PI to install IIS, you can install IIS manually. To install IIS manually, use the following steps:
To install IIS on Windows Server 2012
On the Start page, click the Server Manager tile, and then click OK.
In Server Manager, select Dashboard, and click Add roles and features.
In the Add Roles and Features Wizard, on the Before You Begin page, click Next.
On the Select Installation Type page, select Role-based or Feature-based Installation and click Next
On the Select Destination Server page, select Select a server from the server pool, select your server, and click Next.
On the Select Server Roles page, select Web Server (IIS), and then click Next.
On the Select Features page, note the preselected features that are installed by default, and then select CGI. This selection also installs FastCGI, which is recommended for PHP applications.
Click Next.
On the Web Server Role (IIS) page, click Next.
On the Select Role Services page, note the preselected role services that are installed by default, and then click Next.
You only have to install the IIS 8 default role services for a static-content web server.
On the Confirm Installation Selections page, confirm your selections, and then click Install.
On the Installation Progress page, confirm that your installation of the Web Server (IIS) role and required role services completed successfully, and then click Close.
To verify that IIS installed successfully, type the following into a web browser:
You should see the default IIS Welcome page.
To install IIS on Windows 8
On the Start page, type Control Panel, and then click the Control Panel icon in the search results.
In Control Panel, click Programs, and then click Turn Windows features on or off.
In the Windows Features dialog box, click Internet Information Services, note the preselected features that are installed by default, and then select CGI. This selection also installs FastCGI, which is recommended for PHP applications.
Click OK.
To verify that IIS installed successfully, type the following into a web browser:
You see the default IIS Welcome page.
1.2. Install PHP by using Web PI
The preferred method to install PHP on a Windows or Windows Server computer is to use Web Platform Installer (Web PI).
To install PHP by using Web PI
- Open a browser to the following website: Microsoft Web Platform Installer 3.0.
- Click Download It Now, and then click Run.
- At the top of the Web Platform Installer window, click Products.
- Click Frameworks, and then select the current version of PHP.
- Click Install. The Web Platform Installation page displays the version of PHP and its dependencies that will be installed.
- Click I Accept. Web PI installs the PHP packages.
- Click Finish.
1.3. Download and Install PHP Manually
If you decide to download PHP and install it manually, the procedures in this section guide you the following tasks:
- Download PHP and the WinCache extension.
- Install PHP and WinCache.
- Add the PHP installation folder to the Path environment variable.
- Set up a handler mapping for PHP.
- Add default document entries for PHP.
- Test your PHP installation.
To keep this procedure simple, install the WinCache extension but do not configure it. You will configure and test WinCache in Step 2: Configure PHP Settings.
To download and install PHP and WinCache
- Open your browser to Windows for PHP Download Page and download the PHP non-thread-safe zip package.
- Download the WinCache extension from the List of Windows Extensions for PHP.
- Extract all files in the PHP .zip package to a folder of your choice, for example C:\PHP\ .
- Extract the WinCache .zip package to the PHP extensions folder (\ext), for example C:\PHP\ext . The WinCache .zip package contains one file (Php_wincache.dll).
- Open Control Panel, click System and Security, click System, and then click Advanced system settings.
- In the System Properties window, select the Advanced tab, and then click Environment Variables.
- Under System variables, select Path, and then click Edit.
- Add the path to your PHP installation folder to the end of the Variable value, for example ;C:\PHP . Click OK.
- Open IIS Manager, select the hostname of your computer in the Connections panel, and then double-click Handler Mappings.
- In the Action panel, click Add Module Mapping.
- In Request path, type *.php.
- From the Module menu, select FastCgiModule.
- In the Executable box, type the full path to Php-cgi.exe, for example C:\PHP\Php-cgi.exe .
- In Name, type a name for the module mapping, for example FastCGI.
- Click OK.
- Select the hostname of your computer in the Connections panel, and double-click Default Document.
- In the Action panel, click Add. Type Index.php in the Name box, and then click OK.
- Click Add again. Type Default.php in the Name box, and then click OK.
To test your PHP installation
Open a text editor, for example Notepad, as Administrator.
In a new file, type the following text:
Save the file as C:\inetpub\wwwroot\Phpinfo.php .
Open a browser and enter the following URL:
A nicely formatted webpage is displayed showing the current PHP settings.
1.4. Add Your PHP Application
Once you have IIS and PHP installed, you can add a PHP application to your web server. This section describes how to set up your PHP application on an IIS web server with PHP installed. It does not explain how to develop a PHP application.
To add a PHP web application
Open IIS Manager.
- For Windows Server 2012, on the Start page click the Server Manager tile, and then click OK. On the Server Manager Dashboard, click the Tools menu, and then click Internet Information Services (IIS) Manager.
- For Windows 8, on the Start page type Control Panel, and then click the Control Panel icon in the search results. On the Control Panel screen, click System and Security, click Administrative Tools, and then click Internet Information Services (IIS) Manager.
In the Connections pane, right-click the Sites node in the tree, and then click Add Website.
In the Add Website dialog box, type a friendly name for your website in the Site name box.
If you want to select a different application pool than the one listed in the Application Pool box, click Select. In the Select Application Pool dialog box, select an application pool from the Application Pool list and then click OK.
In the Physical path box, type the physical path of the website’s folder, or click the browse button (. ) to navigate the file system to find the folder.
If the physical path that you entered in step 5 is to a remote share, click Connect as to specify credentials that have permission to access the path. If you do not use specific credentials, select the Application user (pass-through authentication) option in the Connect As dialog box.
Select the protocol for the website from the Type list.
The default value in the IP address box is All Unassigned. If you must specify a static IP address for the website, type the IP address in the IP address box.
Type a port number in the Port text box.
Optionally, type a host header name for the website in the Host Header box.
If you do not have to make any changes to the site, and you want the website to be immediately available, select the Start Web site immediately check box.