Как развернуть php сервер на windows 10

Подробная инструкция по установке, настройке и запуску веб-сервера IIS с PHP и MySQL на Windows. Рассмотрен пример установки всех компонентов с нуля.

Обновлено и опубликовано Опубликовано: 28.11.2019

Используемые термины: IIS, PHP, MySQL.

Чаще всего, PHP и MySQL устанавливается на серверы с Linux. Однако, при необходимости, можно настроить запуск и обработку PHP скриптов на Windows. Версии последней могут быть разные, например, Server 2008/2012/2016/2019 или не серверные системы, такие как, 7/8/10. Данная инструкция подойдет как для чайника, так и опытного специалиста (в качестве шпаргалки).

Устанавливаем IIS
Публикация сайта для PHP
Работаем с PHP
    Устанавливаем
    Настраиваем IIS + PHP
    PHP Manager для управления
Установка MySQL

Установка IIS

Для установки веб-сервера, открываем Диспетчер серверов — переходим в УправлениеДобавить роли и компоненты:

Добавление роли в диспетчере серверов

Если откроется окно с приветствием, нажимаем Далее:

Вступление перед установкой ролей и служб

При выборе типа установки выбираем Установка ролей или компонентов:

Выбор типа установки

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

Выбор целевого сервера

Среди ролей выбираем Веб-сервер (IIS) — во всплывающем окне кликаем по Добавить компоненты:

Выбор ролей сервера

Также среди ролей в подразделе «Разработка приложений» ставим галочку для установки CGI — этот компонент нам нужен для работы PHP:

Установка CGI

При выборе компонентов ничего не меняем — нажимаем Далее:

Выбор компонентов

Откроется окно настройки роли веб-сервера — просто нажимаем Далее:

Роль веб-сервера

Выбор служб ролей — нажимаем далее или, при необходимости, выбираем FTP-сервер:

Выбор служб ролей

В следующем окне ставим галочку Автоматический перезапуск конечного сервера, если требуется и кликаем по Установить:

Подтверждение компонентов установки

Дожидаемся окончания процесса установки.

Сразу после установки IIS запускается автоматически. Но, если что, его можно запустить с помощью команды iisreset:

iisreset /start

* если выполнить данную команду без опций, то она перезапустить веб-сервер.

Также мы можем открыть диспетчер служб (команда services.msc) и перезапустить Службу веб-публикаций:

Служба веб-публикаций

Открываем браузер и вводим адрес http://localhost — должен открыться стартовый портал:

Проверка загрузки стартового сайта

Развертывание отдельного сайта

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

Открываем Диспетчер серверов — кликаем по СредстваДиспетчер служб IIS:

Запуск диспетчера служб IIS

Находим раздел сайты — кликаем правой кнопкой мыши по Добавить веб-сайт…:

Добавление нового сайта в IIS

Заполняем данные для нового сайта:

Данные для нового сайта

* где:

  • Имя сайта — произвольно имя будущего сайта.
  • Физический путь — путь до папки на сервере, где будут расположены файлы сайта.
  • Тип — тип соединения (http или https). Для первого запуска обойдемся http. При необходимости, его можно всегда поменять или использовать оба типа одновременно.
  • IP-адрес — если на сервере много IP-адресов, то мы можем выбрать конкретный, на котором будет работать сайт.
  • Порт — сетевой порт, на котором будет работать сайт. Как правило, это 80 для http или 443 для https.
  • Имя узла — доменное имя сайта, при обращении по которому должен открываться создаваемый сайт.

После заходим в каталог с сайтом (в нашем примере, это C:inetpubwwwrootphp) и создадим в нем файл index.html со следующим содержимым:

<h1>Hello from PHP site</h1>

Открываем браузер и переходим на созданный сайт, например, как в нашей инструкции — http://php.dmosk.ru. Мы должны увидеть страницу с написанным нами текстом:

Загрузка тестовой страницы

Тестовый сайт создан.

PHP

Установка PHP

Для установки php на Windows переходим на страницу загрузки PHP — выбираем нужную нам версию, например, последнюю стабильную и переходим по ссылке для загрузки версии для Windows:

Переходим к загрузке PHP для Windows

Откроется страница с несколькими версиями пакета — там как мы ставим PHP как FastCGI, нам нужна версия «Non Thread Safe» (не потокобезопасная), так как она будет работать быстрее. И так, скачиваем zip-архив на сервер:

Загрузка PHP-архива zip для Windows

Для установка PHP на Windows достаточно просто распаковать содержимое архива в любой каталог, например, C:Program FilesPHP:

Распакованные файла из архива PHP

Делаем копию файла php.ini-production и переименовываем его в php.ini:

Распакованные файла из архива PHP

Открываем на редактирование данный файл и правим следующее:

open_basedir = C:inetpubwwwroot

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 FilesPHP»

Запускаем php с параметром -m:

php -m

Мы должны получить список подключенных модулей:

[PHP Modules]
bcmath
calendar
Core
ctype

Но если мы получим ошибку, связанную с отсутствием файла VCRUNTIME140.dll:

Ошибка при отсутствии файла VCRUNTIME140.dll

… необходимо установить Microsoft Visual C++ Redistributable. Переходим на страницу https://www.microsoft.com/ru-RU/download/details.aspx?id=52685 и скачиваем компонент:

Выбираем версию для загрузки компонента

После загрузки, устанавливаем его на сервер, после чего, снова пробуем вывести на экран модули php:

php -m

Настройка сайта на IIS для работы с PHP

И так, веб-сервер поднят, PHP установлено, сайт работает. Настроим связку IIS + PHP. Открываем панель управления IIS — переходим к созданному сайту и кликаем по Сопоставления обработчиков:

Переход к Сопоставления обработчиков

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

Переходим к добавлению сопоставления модуля

Заполняем поля:

Заполняем полня для настройки сопоставления модуля

* где:

  • Путь запроса — путь к файлам, при вызове которых действует сопоставление. В данном примере для всех файлов, заканчивающихся на php.
  • Модуль — действующий модуль для обработки запроса.
  • Исполняемый файл — файл, который будет выполнять обработку запроса. В данном примере мы выбрали файл из скачанного и распакованного нами архива PHP.
  • Имя — произвольное имя для сопоставления.

Нажимаем OK и подтверждаем действие. Сопоставление создано.

Теперь заходим в Документ по умолчанию:

Переход к документам по умолчанию

… и добавляем новый документ:

Добавляем файл по умолчанию

* в данном примете мы указываем, что по умолчанию сервер будет искать файл index.php, если таковой не указан явно в запросе.

Открываем в проводнике папку, в которой находятся файлы сайта (в нашем примере, C:inetpubwwwrootphp). Создаем файл index.php с содержимым:

Открываем браузер и снова переходим на наш сайт — мы должны увидеть страницу с информацией о php:

phpinfo в браузере

PHP Manager в IIS

Для того, чтобы упростить настройку PHP мы можем установить диспетчер PHP для IIS. Для этого переходим по ссылке https://www.iis.net/downloads/community/category/manage и переходим по ссылке для скачивания стабильной версии php-менеджера:

Скачиваем PHP Manager для IIS

Скачиваем дополнение:

Загрузка дополнения PHP Manager для IIS

Выполняем установку на сервере, запустив загруженный файл. Открываем диспетчер управления IIS — мы должны увидеть PHP Manager:

PHP Manager для IIS

Установка MySQL

MySQL для Windows можно скачать бесплатно. Переходим на страницу https://dev.mysql.com/downloads/mysql/ — выбираем операционную систему Microsoft Windows — кликаем по Go to Download Page:

Выбор операционной системы и переход к загрузке MySQL

На следующей странице выбираем для скачивания mysql-installer-community:

Скачиваем MySQL для Windows

В открывшемся окне кликаем по No thanks, just start my download:

Пропускаем регистрации и скачиваем сервер

Начнется загрузка файла для установки MySQL. Дожидаемся скачивания и запускаем установочный файл — в открывшемся окне выбираем Server only:

Выбираем установку сервера MySQL

В следующем окне кликаем по Execute:

Все готово для установки MySQL на Windows

… и дожидаемся установки СУБД:

Установка MySQL завершена

Откроется окно конфигурации MySQL — нажимаем Next:

Начало настройки MySQL сразу после установки

Выбираем установку одиночного сервера MySQL:

Выбираем вариант установки сервера

Оставляем все значения по умолчанию для настроек сети:

Сетевые настройки для MySQL

Требуем сложные пароли:

Настройка сложности пароля

Вводим дважды пароль для пользователя root:

Вводим новый пароль для пользователя root

* также, на данном этапе мы можем сразу добавить новых пользователей.

Устанавливаем СУБД как сервис и стартуем его:

Установка MySQL в качестве службы Windows

Настройки готовы для применения — нажимаем Execute:

Все готово для конфигурирования MySQL

Дожидаемся применения настроек и кликаем по Next:

Конфигурирование MySQL завершено

Настройка завершена:

Настройка СУБД завершена

Установка завершена — нажимаем Finish.

Установка MySQl на Windows выполнена успешно

Сервер баз данных готов к использованию.

По умолчанию, PHP поддерживаем mysql — в этом можно убедиться на странице phpinfo, найдя раздел mysqlnd:

mysqlnd должен быть включен в php

Этот раздел содержит примечания и подсказки к установке PHP, связанной с
Apache 2.x на системах Microsoft Windows.

Замечание:

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

Крайне рекомендуется обратиться к » 
Документации Apache, чтобы получить базовое представление о сервере
Apache 2.x. Также подумайте о чтении » 
Примечаний для Windows для Apache 2.x перед чтением этого руководства.

Загрузите последнюю версию
» Apache 2.x
и подходящую версию PHP. Следуйте
шагам ручной установки
и возвращайтесь, чтобы продолжить интеграцию PHP и Apache.

Существует три способа настроить PHP для работы с Apache 2.x в Windows.
PHP можно запускать как обработчик, как CGI или под FastCGI.

Замечание: Помните, что при указании путей
в конфигурационных файлах Apache под Windows, все обратные слеши, например,
c:directoryfile.ext должны быть изменены на прямые:
c:/directory/file.ext. Для путей с директориями также может понадобиться слеш в конце.

Установка в качестве обработчика Apache

Чтобы загрузить модуль PHP для Apache 2.x, необходимо вставить следующие
строки в файл конфигурации Apache httpd.conf:

Пример #1 PHP и Apache 2.x в качестве обработчика

# до PHP 8.0.0 имя модуля было php7_module
LoadModule php_module "c:/php/php8apache2_4.dll"
<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>
# укажите путь до php.ini
PHPIniDir "C:/php"

Замечание:

В приведённых выше примерах необходимо подставить фактический
путь к PHP вместо C:/php/. Убедитесь, что
файл, указанный в директиве LoadModule, находился в указанном месте.
Используйте php7apache2_4.dll для PHP 7 или
php8apache2_4.dll для PHP 8.

Запуск PHP как CGI

Настоятельно рекомендуется обратиться к
» Документации Apache CGI
для более полного понимания того, как запускать CGI в Apache.

Чтобы запустить PHP как CGI, файлы php-cgi должны быть помещены в
каталог, обозначенный как каталог CGI с использованием директивы ScriptAlias.

Строку #! необходимо будет поместить в файлы PHP, которые
указывают на расположение бинарного файла PHP:

Пример #2 PHP и Apache 2.x как CGI

#!C:/php/php.exe
<?php
  phpinfo();
?>

Внимание

Используя установку CGI, ваш сервер открыт перед несколькими возможными уязвимостями. Пожалуйста, ознакомьтесь с разделом «Безопасность CGI» чтобы узнать, как можно защитить себя от таких атак.

Запуск PHP под FastCGI

Запуск PHP под FastCGI имеет ряд преимуществ перед запуском как CGI.
Настройка таким способом довольно проста:

Загрузите mod_fcgid с
» https://www.apachelounge.com.
Бинарные файлы Win32 доступны для загрузки с этого сайта. Установите модуль
в соответствии с прилагаемой к нему инструкцией.

Настройте свой веб-сервер, как показано ниже, позаботившись о том, чтобы все
пути отражали то, как вы провели установку в своей конкретной системе:

Пример #3 Настройка Apache для запуска PHP как FastCGI

LoadModule fcgid_module modules/mod_fcgid.so
# Где находится ваш файл php.ini?
FcgidInitialEnv PHPRC        "c:/php"
<FilesMatch .php$>
    SetHandler fcgid-script
</FilesMatch>
FcgidWrapper "c:/php/php-cgi.exe" .php

Файлы с расширением .php теперь будут исполняться обёрткой PHP FastCGI.

wolfeh1994 at yahoo dot com

9 years ago


Please for the love of god, download the threaded version. I spent over an hour trying to figure out why php5apache2.dll could not be found, and while desperately looking through manuals I went into the php 5 structure and found that it doesn't exist in the non-threaded version.

This really could use a mention somewhere other than the PHP 5 structure, like the paragraph to the left of the homepage which talks about which PHP version to choose, or this part of the manual which covers Apache... Anywhere but structure, seriously. I would have never guessed to look there.


ohcc at 163 dot com

7 years ago


If you come with an error like this: Wrapper xxxx cannot be accessed: blah blah blah when starting Apache.

You have 3 choices to solve this problem. Any one of them would work.

1. Reinstall your applictions in paths that do not contain spaces.

2. Place a backslash before every space in the path set to the FcgidWrapper directive in httpd.conf, like:

FcgidWrapper "C:/Program Files/PHPServer/PHP/php-cgi.exe" .php

3. Use mklink (or junction for windows XP/2003) to create a symbol link to the path of php-cgi.exe's containing folder.

run cmd.exe and type this command:

mklink /j C:php "C:Program FilesPHPServerPHP".

or this command if you are on Windows XP/2003

junction C:php "C:Program FilesPHPServerPHP"

Remember this : you need to download junction.exe to use it. Don't know where to download? Google it.

Then the FcgidWrapper directive should be like this:

FcgidWrapper "C:/php/php-cgi.exe" .php

Don't forget to change the paths above to your working paths.


farinspace

12 years ago


Running PHP under FastCGI:

Besides the following in your httpd.conf

    LoadModule fcgid_module modules/mod_fcgid.so 
    FcgidInitialEnv PHPRC "c:/php"
    AddHandler fcgid-script .php 
    FcgidWrapper "c:/php/php-cgi.exe" .php

Remember to add the following to the default <Directory "C:/apache/htdocs"> block (or virtual host blocks):

    Options ExecCGI


Anonymous

8 years ago


With Apache 2.4 in Windows, it seems that PHPIniDir directive must come before LoadModule directive to be used. Also, name of the DLL file seems to be php5apache2_4.dll, not php5apache2.dll.

This configuration in httpd.conf works for me (Apache 2.4.10, PHP 5.6.5):

PHPIniDir "C:PHP"

LoadModule php5_module "c:/php/php5apache2_4.dll"
<FilesMatch .php$>
      SetHandler application/x-httpd-php
</FilesMatch>


mjm at alum dot mit dot edu

15 years ago


If you use the PHP 5 installer, you'll notice that it uses the wrong type of slash on Windows!

Change C:/Program Files/PHP/" to C:Program FilesPHP" and everything works great!


Anonymous

13 years ago


If anybody here encounters an error regarding PHPIniDir, change PHPIniDir "C:/php/" to PHPIniDir "C:php".

Cameron

11 years ago


Here is yet another aspect of the "faulting module php5ts.dll" crash when trying to start apache.
I installed Apache 2.2.18, Mysql 5.1.57 and PHP 5.2.17 (apache module, VC6 thread-safe - initially with no extensions) on a fresh WinXP SP3 system. The versions chosen were because I was trying to replicate as near as possible apps on my Linux server.

Everything configured and ran properly without php extensions, so I then reran the msi installer and chose the necessary extensions.  I reconfigured httpd.conf  but apache then just kept crashing.
Eventually I came across the "fix" mentioned elsewhere "copy libmysql.dll to apache folder" and suddenly it worked. But why? I checked and the php installation folder was in the system path. The answer was simply that I had never rebooted. It seems that whatever process controls windows services only reads the path at boot time.  I was thrown by assuming that if I started httpd from the command line then it would inherit that path.

Here are a few diagnostic tips that helped me along the way:

Try the CLI command:
php -m
and see that the command line version loads all the modules you asked for.

in php.ini, enable
display_errors = On
and
display_startup_errors = On
The latter pops up a window saying which extension it has trouble loading. Of course it is not perfectly clear, because it says something like 'unable to load "C:phpextphp_mysql.dll" - The specified module could not be found'. It lies - it really does find that dll, but it must have failed on the dependency of libmysql.dll.


a solution for simpletons like me

10 years ago


Installing Apache and PHP on Windows 7 Home Premium on a Gateway NV75S laptop with a quad AMD A6-3400M

All I need to do with these programs is to test my website out on my laptop.  I have HTML and PHP files. I do not need MySQL as I use html5 storage.

Getting and installing Apache

1  In your browser go to h t t p : / / h t t p d . a p a c h e . o r g / d o w n l o a d . c g i
   (without the spaces)
2  Click on  httpd-2.2.22-win32-x86-no_ssl.msi
   (this is a self-installing executable file without crypto ... no Secure Socket Layer)
   (2.2.22 was the latest version on April 25, 2012)
3  Click on the httpd-2.2.22-win32-x86-no_ssl.msi file after it downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the license agreement
6  Click Next
7  Click Next
8  Type localhost in the top box
9  Type localhost in the middle box
10 Type admin@localhost.com in the bottom box
11 Click Next
12 Click Next
13 Click Next
14 Click Install and wait
15 Cick Yes to allow the program to make changes
16 Click Finish

Testing Apache

1  Type localhost in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t
   (without the spaces)
2  The message It works! should appear.

Getting and installing PHP

1  In your browser go to h t t p : / / w i n d o w s . p h p . n e t / d o w n l o a d /
   (without the spaces)
2  Click on the Installer link under PHP 5.3 (5.3.10)   VC9 x86 Thread Safe
   (Ignore the Do NOT use VC9 version with apache.org binaries comment on the side panel)
3  Click on the php-5.3.10-Win32-VC9-x86.msi file after in downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the License Agreement
6  Click Next
7  Click Next
8  Click Apache 2.2.x Module
9  Click Next
10 Click Browse
11 Double click Apache Software Foundation
12 Double click Apache 2.2
13 Double click conf
14 Click OK
15 Click Next
16 Click Next
17 Click Install and wait
18 Cick Yes to allow the program to make changes
19 Click Finish

Testing PHP with Apache

1  Open Notepad
2  Type 'left bracket character'?php phpinfo(); ?'right bracket character'
3  Save the file to C:Program Files (x86)Apache Software FoundationApache2.2htdocs as test.php
4  Type localhost/test.php in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t / t e s t . p h p
5  A table with title PHP Version ... should appear

DONE


compleatguru at gmail dot com

9 years ago


I am using Windows 8 x64, running Apache 2.2 and php 5.4.20

I found that it is necessary to add System Environment Variable PHPRC=[PHP path], so that php.ini is loaded using your PHP path, instead of C:Windows.

This is how I do for my laptop
Go to Control PanelSystem and SecuritySystemAdvanced System SettingsEnvironment Variables

Add New System Variable
Name: PHPRC
Value: C:php-5.4.20

Hope it relieve those who keep having empty string for Loaded Configuration File under phpinfo();


bdav

10 years ago


After spending few hours finally figured out that PHPINIDir path should be in single quotes and with backslash and php module with double quotes and regular slashes:

PHPIniDir 'c:appsphp'
LoadModule php5_module "c:/apps/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php


Nick

12 years ago


After using the Windows installer for Apache 2.2 and PHP 5.3.2, and installing PHP as an Apache module (not CGI), Apache would crash and fail to start. There were two problems with the configuration files for Apache and PHP.

First, make sure your Apache configuration file reads something similar to:

LoadModule php5_module "C:/Program Files/PHP/php5apache2_2.dll"
PHPIniDir "C:/Program Files/PHP/"

While other users have disabled some or all of the MySQL extensions to prevent all three from running at the same time, I have all of them enabled. However, I do not have PostgreSQL, so I needed to comment out loading the php_pgsql.dll in my php.ini file, as follows:

;[PHP_PGSQL]
;extension=php_pgsql.dll

This stopped Apache from crashing and started successfully.


a user

7 years ago


If you are having issues getting the PHPIniDir or LoadModule directives to work and all the suggestions already given do not help, double-check if you are not using fancy quotes around your paths (‘ ’  “ ”).

This happened to me because I copied the statements from a random website. In my text editor the difference was barely noticeable, but to Apache it certainly is!

For example, this will not work:
PHPIniDir “C:/PHP7”

But this will work:
PHPIniDir "C:/PHP7"


ohcc at 163 dot com

7 years ago


If you come with an error like this: Wrapper xxxx cannot be accessed: blah blah blah when starting Apache.

You have 3 choices to solve this problem. Any one of them would work.

1. Install your applictions in paths that do not contains spaces.

2. Place a backslash before every space in the path set to Wrapper, like:

FctidWrapper "C:/Program Files/PHPServer/PHP/php-cgi.exe" .php

3. Use mklink (or junction for windows XP/2003) to create a link to the path you have installed php in.

run cmd.exe and type this command:

mklink /j C:php "C:Program FilesPHPServerPHP".

or this command if you are on Windows XP/2003

junction C:php "C:Program FilesPHPServerPHP"

Remember this : you have to download online to use this application. Don't know where to download? Go and Google it.

Then the FctidWrapper directive should be like this:

FctidWrapper "C:/php/php-cgi.exe" .php

Don't forget to change the paths above to your working paths.


BuggedApache

7 years ago


Windows Apache 2.4.12 (x64) PHP 5.6.5 (x64)
If your Apache still outputs code instead of parsing a script. Make sure you put a trailing "" at the end of the PHPIniDir value and use ONLY "" in path to PHPIniDir. And "/" in LoadModule. A very subtle "feature" of Apache module. Lost several hours after upgrading to apache x64 to resolve the issue.

httpd.conf
###############################################
PHPIniDir "C:foldertoholdphp"
LoadModule php5_module "C:/folder/to/hold/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
###############################################


kynetikmedia at gmail dot com

8 years ago


****Installed and Working 1- Fell Swoop - UPDATED****
Installed on Windows 8.1 XPS 12 - Dell 8GB RAM 128GB SSD -
Notes - Complications due to Apache latest version causes issues with the PHP handler on install.  Following below will get it run right off the bat. 

Getting and installing Apache

1  In your browser go to h t t p : / / h t t p d . a p a c h e . o r g / d o w n l o a d . c g i
   (without the spaces) - You will need to go 'Other Files' , 'Binaries' , 'W32', and then your installer MSI will be listed as below. 
2  Click on  httpd-2.2.25-win32-x86-no_ssl.msi
   (this is a self-installing executable file without crypto ... no Secure Socket Layer)
   (2.2.25was the latest version on June 4, 2014)
3  Click on the httpd-2.2.25-win32-x86-no_ssl.msi file after it downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the license agreement
6  Click Next
7  Click Next
8  Type localhost in the top box
9  Type localhost in the middle box
10 Type admin@localhost.com in the bottom box
11 Click Next
12 Click Next
13 Click Next
14 Click Install and wait
15 Cick Yes to allow the program to make changes
16 Click Finish

Testing Apache

1  Type localhost in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t
   (without the spaces)
2  The message It works! should appear.

Getting and installing PHP

1  In your browser go to h t t p : / / w i n d o w s . p h p . n e t / d o w n l o a d /
   (without the spaces)
2  Click on the Installer link under PHP 5.3 (5.3.10)   VC9 x86 Thread Safe
   (Ignore the Do NOT use VC9 version with apache.org binaries comment on the side panel)
3  Click on the php-5.3.10-Win32-VC9-x86.msi file after in downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the License Agreement
6  Click Next
7  Click Next
8  Click Apache 2.2.x Module
9  Click Next
10 Click Browse
11 Double click Apache Software Foundation
12 Double click Apache 2.2
13 Double click conf
14 Click OK
15 Click Next
16 Click Next
17 Click Install and wait
18 Cick Yes to allow the program to make changes
19 Click Finish

Testing PHP with Apache

1  Open Notepad
2  Type 'left bracket character'?php phpinfo(); ?'right bracket character'
3  Save the file to C:Program Files (x86)Apache Software FoundationApache2.2htdocs as test.php
4  Type localhost/test.php in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t / t e s t . p h p
5  A table with title PHP Version ... should appear

DONE


tmnuwan12 at yahoo dot com

9 years ago


I am very new to PHP. I was looking to start a Drupal project and spend almost 4 hours to get Apache and Drupal talk each other.
What I found out was there are lots of mismatch in documentation and snapshots.

As I am using Windows I found out following two installation bundles works without any issue.

php-5.3.28-Win32-VC9-x86.msi
httpd-2.2.25-win32-x86-openssl-0.9.8y.msi

Make sure you install your packages directly into into C: drive in Windows machine (If there are spaces in the file paths it would cause issues).

Hope this would help someone.


Bechesa at gmail dot com

10 years ago


Just a note
It might be important you include the absolute path to the php.ini  file inside the httpd.conf file so that php may load all the module(s).

below is an example

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir 'C:PHPphp.ini'
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

OS: windows 2008
webserver: apache2.2


Z Carlos at Fortaleza

11 years ago


A Thread Safe version should be used if you install PHP as an Apache module. The Non Thread Safe version should be used if you install PHP as a CGI binary.

bradley dot henke at colorado dot edu

11 years ago


I was able to get apache up and running without any problems. Then I tried installing php and it crashed trying to read "C:/php/php5apache2.dll".

Fixed the problem by switching it to "C:/php/php5apache2_2.dll"

Hope that helps!


Michael

12 years ago


The value for FcgidWrapper cannot contain spaces..

This won't work:

FcgidWrapper "c:/program files (x86)/php/php-cgi.exe" .php

But this will:

FcgidWrapper "c:/progra~2/php/php-cgi.exe" .php


Steve

12 years ago


I also had a problem with the PHPIniDir declaration.  This is with Apache 2.2 on XP.  I had to include a final slash, as in PHPIniDir "C:Program Filesphp".  Apache failed to start if I did not include the slash after php.

gmatwy at gmail dot com

6 years ago


version
httpd-2.4.23-win32-VC14.zip
php-5.6.26-ts-Win32-VC11-x86.zip

install path c:/wamp/
php path c:/wamp/php
apache path c:/wamp/Apache24
used as Apache handler

modify as below

#below for apache
#modify c:/ to c:/wamp/
#modify ServerName to localhost:80 and remove#
#DirectoryIndex insert index.php

#below for php
#rename file php.ini-production to php.ini
LoadModule php5_module "C:/wamp/php/php5apache2_4.dll"
PHPIniDir "C:/wamp/php/"

AddType application/x-httpd-php .php
AddType application/x-httpd-php .html

AddHandler application/x-httpd-php .php

And things goes well !


nicolas dot grasset at gmail dot com

13 years ago


Here is how I created a silent install for Apache2.2 and PHP5.2.10 on Windows XP (running on a MacBook Pro):

Download Apache2 and PHP5 installer files in a directory and update the msi file names in the following commands.

To have PHP installer find Apache2, do not forget APACHEDIR!

msiexec /i apache_2.2.11-win32-x86-no_ssl.msi /passive ALLUSERS=1 SERVERADMIN=admin@localhost SERVERNAME=localhost SERVERDOMAIN=localhost SERVERPORT=80 INSTALLDIR=c:apache
msiexec /i php-5.2.10-win32-installer.msi /qn APACHEDIR=c:apache INSTALLDIR=c:php ADDLOCAL=ext_php_mssql,apache22
net stop "Apache2.2"
net start "Apache2.2"


packard_bell_nec at hotmail dot com

15 years ago


If you install PHP as an Apache CGI binary, you can add:
AddHandler cgi-script .php
into Apache httpd.conf, and add shebang line to every PHP scripts like:
#!php
<?php
phpinfo
();
?>
. But adding shebang line has a disadvantage that if you decided to install PHP as an Apache module afterwards, then the shebang line WILL appear in the web page.
In fact, you do NOT need to add shebang line to every PHP script even if you install PHP as an Apache CGI binary, because you can add:
ScriptInterpreterSource Registry-Strict
into Apache httpd.conf, and make the registry file and merge it like:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT.phpShellExecCGICommand]
@=""C:\Program Files\PHP\php-cgi.exe""
. Then you will NOT need to change the PHP scripts which do not contain shebang line.

Maw

10 years ago


Good God finally I was able to make PHP 5.2 work on Apache 2.4. For those still having problems with "You don't have permission to run php-cgi.exe", you must replace "Order allow,deny" and "Allow from all" from the PHP directory block with "Require all granted". They must have changed the format with Apache 2.4 since the old method used to work just fine for me before.

So the usual method of setting up CGI, I'm sure you already know that you should add these 3 lines to httpd.conf:
ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"

And now add the directory for PHP:
<Directory "c:/php">
    AllowOverride None
    Options None
    Require all granted
</Directory>

Important: Notice that instead of "Order allow,deny" and "Allow from all" added into the PHP directory as usual, I replaced them with "Require all granted" as I mentioned above.


lebovskiy at ua dot fm

12 years ago


I install httpd-2.2.17-win32-x86-openssl-0.9.8o.msi and after
php-5.3.3-Win32-VC9-x86.msi on WinXP SP3. PHP installation add to httpd.conf next lines:

LoadModule php5_module "C:/PHP/php5apache2_2.dll
"PHPIniDir "C:/PHP"

After it Apache don`t starts. If remove PHPIniDir line Apache  starts ok, but C:/PHP/php.ini don`t loaded. So you can`t use any extension (for me it's MySQL).

I uninstall VC9 version and install VC6 (php-5.3.3-Win32-VC6-x86.msi) version. All works fine now.


halmai

12 years ago


I wanted to install PHP5.3 for Apache2.2 with PostgreSql 9.0 support on WindowsXP. It took me hours to solve it.

The following possible problems occur:
- You should use the VC6-compiled version of php instead of VC9. The later one does not work properly with apache.
- the postgres handler dlls are not working in PHP5.3.

The symptom was a misleading and very confusing error message:

Unable to load dynamic library 'c:Progra~1PHPextphp_pgsql.dll'

The dll itself was there but when it started to load the other dll (libpq.dll) from the php directory then this caused an error. This error was misinterpreted internally in the above message.

The solution was NOT to use the libpq.dll from php but use it from postgres distribution instead.

For this purpose I inserted the following line into the apache httpd conf:

LoadFile "C:/Progra~1/PostgreSQL/9.0/bin/libpq.dll"

This preloads the dll. When php_pgsql.dll would load his own libpq.dll, then there is the preloaded version of this file in the memory already. This prevents us from using the bad version of dll.

I hope I helped.


Guillermo Tallano

9 years ago


Hi guys,
In my case, it work right away when I change the version to thread-safe.
I spent some time trying the different things that were posted here and I was kind of lazy about downloading a different version, but once I test it with a thead-safe it started right away. So be sure you try this.

I was on Apache 2.2, XP and php 5.2.17 thread-safe

This is my conf:
LoadModule php5_module "c:/php5/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
#configure the path to php.ini
PHPIniDir 'C:php5'

Good luck!


Anonymous

13 years ago


i followed henke37's way to for the httpd.conf

I added all this at the very end of httpd.conf

# For PHP 5
#load the php main library to avoid dll hell
Loadfile "C:php-5.2.8-Win32php5ts.dll"

#load the sapi so that apache can use php
LoadModule php5_module "C:php-5.2.8-Win32php5apache2_2.dll"

#set the php.ini location so that you don't have to waste time guessing where it is
PHPIniDir "C:php-5.2.8-Win32"

#Hook the php file extensions
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

Also i didn't use short open tags as they are disabled in
"php.ini-recommended" if you don't change anything
So use this to test
<?php
phpinfo
();
?>
NOT
<? phpinfo(); ?> short open tags

added my php directory to the PATH system variable and i start apache manually not as a service

It works for me hope it helps you!


Amaroq

9 years ago


Like someone else mentioned, on the Windows download page for PHP, ignore the warning about not downloading the VC9 compiled installers for the Apache.org version of Apache.

Whoever wrote that is guaranteeing that people install a PHP that breaks their Apache server. (On Windows 7 anyway.) The installer failed to write the correct path info to httpd.conf, and even after fixing that manually, Apache wouldn't start because of missing dlls.

Ignore that dumb warning and get the newest installer anyway. Everything just plain works with no hassle and no hunting down dll files over google.


Cooldude

11 years ago


Also had an exception problem when trying to use mysql with apache and php5.

I had to add:

"<my MySQL folder>bin" folder to path
"<my php folder>ext" to path

that fixed it


alx dot suvorov at gmail dot com

4 years ago


For PHP 7 configuration just add these lines to the end of httpd.conf file (of Apache):

PHPIniDir "/alex/apps/php-7.2.3/"
LoadModule php7_module "C:/alex/apps/php-7.2.3/php7apache2_4.dll"
<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>

Here "/alex/apps/php-7.2.3/" is PHP path.

Then:
1. Rename php.ini-development or php.ini-production to php.ini
2. Uncomment / set extension_dir parameter in php.ini
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"

You are set. Just re/start Apache server (httpd -k restart).


jangirashok at gmail dot com

8 years ago


Can anyone tell me: Why PHP + Apache 2.2.x installation is such a big deal. I am a Java Developer and currently I am trying to learn PHP, but I am not able to install PHP and use it the way we use Java. I could use steps mentioned in comments and run home.php from htdocs folder of apache. But, could anyone please tell me DO I HAVE TO PUT EVERY FILE IN THE SAME FOLDER? Can't I make my workbench where I can put a good project hierarchy and use it like other languages. Its horrible. May be my question is little silly, but I need help for sure.
Thanks...

Благодаря WSL вы получите мощную платформу, где легко сможете заниматься разработкой веб-проектов. Вам больше не нужно думать, где и какие программы скачать для создания локального сервера на вашей рабочей машине, не нужно тратить время на поиск и установку. Microsoft сделала большой шаг для удобства разработчиков, представив подсистему Linux в Windows 10 WSL 2.

В новой подсистеме WSL2 доступ к полной оболочке Linux занимает не более секунды. Это означает, что теперь вы можете работать над проектами на основе Linux внутри Windows с высокой скоростью. 

В данном руководстве рассмотрим, как в подсистеме Windows для Linux (WSL) можно настроить веб-сервер LAMP (Apache, MySQL, PHP) для локальной разработки ваших веб-проектов.

  • Windows — выступает как основная ОС, в ней будут работать такие программы как VScode, PhpStorm, SublimeText3, браузеры, консоль и т.д.
  • Ubuntu — как web-сервер и другое программное обеспечение (PHP, Apache, mysql, git и т.д.), управляется консолью Windows 10.

Между этими двумя ОС будут общие файлы, папки, которые мы можем легко редактировать в Windows.

Включение подсистемы Windows для Linux.

Для включения компонента «Подсистема Windows для Linux» в Windows 10 необходимо выполнить следующие действия:

Шаг 1:  С помощью команды: optionalfeatures в диалоговом окне «Выполнить» откройте «Компоненты Windows».

Шаг 2:  Включите опцию «Подсистема Windows для Linux».

Шаг 3:  Перейдите в Microsoft Store  загрузите и установите приложение Ubuntu для Windows.

Перейдите в Microsoft Store  загрузите и установите приложение Ubuntu для Windows

Шаг 4: C помощью меню «Пуск» запустите Ubuntu. В окне терминала, при первом запуске нужно будет ввести новое имя UNIX пользователя (username) и пароль (password).

 C помощью меню «Пуск» запустите Ubuntu

Подробней как это сделать, мы рассмотрели в руководствах:

  •  Как установить WSL 2 подсистему Windows для Linux в Windows 10
  •  Как установить Wsl 1 подсистему Windows для Linux.
  •  Официальная инструкция от microsoft.

Создание директории для веб-проекта.

При использовании WSL 1 желательно помещать файлы  проекта на диски файловой системы Windows —  C, D, E. Если вы будете использовать WSL 2, вы можете также использовать локальные диски или создать директорию для сайта в файловой системе Linux.

Шаг 5: Создайте в Проводнике Windows 10, директорию для сайта (проекта) test.local:

С:Projectstest.localpublic_html

Создайте в Проводнике Windows 10, директорию для сайта (проекта) test.local:

Если вы будете использовать WSL 2 рекомендуется создать директорию для сайта в файловой системе Linux. В этом случае папку проекта поместим сюда: homemainprojectstest.localpublic_html

Для этого выполним команду: 

sudo mkdir -p /home/main/projects/test.local/public_html

Где замените «main» на имя UNIX пользователя созданного при первом запуске wsl.

Во избежание проблем с доступом выполните команду:

sudo chmod -R 777 /home/main

Здесь также замените «main» на ваше имя пользователя UNIX.

Если вы будете использовать WSL 2 рекомендуется создать директорию для сайта в файловой системе Linux.

Это избавит от ошибок и обеспечит максимальную производительность.

Шаг 6: Как получить доступ к файлам WSL Linux из проводника Windows 10.

Находясь в каталоге Linux FS, введите:

explorer.exe .

Откроется окно проводника, расположенное внутри вашего дистрибутива Linux.

Подробнее в нашей статье:  Доступ к файлам WSL Linux с помощью Проводника Windows 10

Как получить доступ к файлам WSL Linux из проводника Windows 10.

Также, чтобы удобно было работать с каталогами файловой системой Linux вы можете установить в Ubuntu, например, «Midnight Commander»:

sudo apt install mc

Запуск Midnight Commander осуществляется посредством ввода команды:

mc

Установка необходимых программ в Ubuntu для Windows 10.

Шаг 7: C помощью меню «Пуск» запустите Ubuntu.

Шаг 8: Обновите локальный индекс apt пакетов в Ubuntu выполнив команду:

sudo apt update

Обновите локальный индекс apt пакетов в Ubuntu выполнив команду:

Шаг 9: После чего необходимо обновить установленное программное обеспечение:

sudo apt upgrade

На запрос «Do you want to continue? [Y/n]» нажмите клавишу Y.

Установка необходимых программ в Ubuntu для Windows 10.

Установка Apache.

Веб-сервер Apache используют более половины всех действующих веб-сайтов. Это очень мощный и гибкий инструмент.

Шаг 10: Установим Apache выполнив команду:

sudo apt install apache2

Вы увидите список пакетов, которые будут установлены, а также объём места на диске которое они займут. Нажмите Y для продолжения установки.

wsl 2 Установка Apache.

Установка MySQL сервера.

MySQL — система управления базами данных. Она организует и обеспечит доступ к базам данных, где сайт может хранить информацию.

Шаг 11: Установим MySQL сервер:

sudo apt install mysql-server

Нажмите Y для продолжения установки. После завершения установки нам потребуется выполнить некоторые дополнительные команды, чтобы настроить наше окружение MySQL

Wsl 2 Установка MySQL сервера

Шаг 12: Установим php и другие пакеты, необходимые для веб-разработки:

PHP это компонент, отвечающий за обработку кода для отображения динамического контента. 

sudo apt install php libapache2-mod-php php-mysql php-xml php-curl

Примечание: Если необходимо установить определенную версию php, например 7.4.x, необходимо выполнить команду:

sudo apt install php7.4 libapache2-mod-php7.4 php7.4-mysql php7.4-xml php7.4-curl

Установим php и другие пакеты, необходимые для веб-разработки:
Включим модуль Mod rewrite в Apache:

Коротко, mod_rewrite — это модуль для веб-сервера Apache, выполняющий функцию преобразования URL.

Шаг 13: Выполните команду:

sudo a2enmod rewrite

Включим модуль Mod rewrite в Apache:

Изменение метода аутентификации MySQL пользователя root.

Необходимо изменить метод аутентификации MySQL для пользователя root выполнив следующие действия:

Шаг 14: Запустим службу mysql.

sudo service mysql start

Wsl Запустим службу mysql.

Шаг 15: Подключимся к серверу MySQL под стандартным пользователем root, который был создан при установке MySQL на ваш компьютер:

sudo mysql -uroot -p

Шаг 16: При запросе пароля нажмите Enter, т.к. по умолчанию пользователь root, созданный при установке, не имеет пароля.

 При запросе пароля нажмите Enter

Примечание: На серверах Ubuntu, использующих MySQL ( 5.7 и более поздние версии), аутентификация root пользователя происходит с помощью плагина auth_socket, а не с помощью пароля. Это во многих случаях повышает безопасность, но, может усложнить настройку доступа к root пользователю для phpMyAdmin и др. программ.

Шаг 17: Чтобы проверить метод аутентификации, который задействован для пользователя root, выполните команду:

SELECT user, authentication_string, plugin, host FROM mysql.user WHERE user="root";

проверить метод аутентификации, который задействован для пользователя root,

Шаг 18: Если в ответе на запрос вы видите используется аутентификация с помощью плагина auth_socket, необходимо изменим эту настройку. Для этого введём команду:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';

Шаг 19: Выполним команду FLUSH PRIVILEGES, которая применит внесённые изменения:

FLUSH PRIVILEGES;

аутентификация с помощью плагина auth_socket

Создание базы данных.

Шаг 20: Создадим базу данных для веб-проекта test.local. Для этого введем в командной строке MySQL следующую команду:

CREATE DATABASE testlocal;

Шаг 21: Для завершения работы с командной строкой MySQL выйдем из неё:

exit

Создадим базу данных для веб-проекта test.local.

Установка phpMyAdmin.

Шаг 22: Выполняем команду:

sudo apt install phpmyadmin

Wsl 2 Установка phpMyAdmin.

Шаг 23: В первом диалоговом окне, нажмите пробел чтобы выбрать Apache, далее нажмите клавишу Tab, а затем Enter.

В первом диалоговом окне, нажмите пробел чтобы выбрать Apache, далее нажмите клавишу Tab, а затем Enter.

Шаг 24: Выберите Yes, для настройки базы данных на запрос использовать dbconfig-common.

Укажите пароль пользователя MySQL root.

Шаг 25: Укажите пароль пользователя MySQL root.

пароль пользователя MySQL root.

Шаг 26: Подтвердите пароль

Шаг 27: Включим необходимые расширения PHP:

sudo phpenmod mcrypt
sudo phpenmod mbstring

Включим необходимые расширения PHP:

Шаг 28: Перезапустите Apache:

sudo service apache2 restart

Теперь вы можете получить доступ к phpMyAdmin по следующему URL: http://localhost/phpmyadmin/ Вы можете войти в систему, используя имя пользователя root и пароль root, настроенные во время установки MySQL.

URL: http://localhost/phpmyadmin/

Настройка виртуальных хостов в Apache.

В Ubuntu файл настроек виртуальных хостов Apache находятся по следующему пути /etc/apache2/sites-available/*.conf. В Apache уже настроен один виртуальный хост по умолчанию в файле 000-default.conf. Возьмем данный файл за основу.

Шаг 29: Создайте копию файла 000-default.conf выполнив команду:

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/test.local.conf

Шаг 30: Внесем изменения в файл test.local.conf, для этого используем, редактор nano:

sudo nano /etc/apache2/sites-available/test.local.conf

Wsl 2 Настройка виртуальных хостов в Apache.

Содержимое файла test.com.conf после правок для Wsl 2 если вы создали директорию для сайта в файловой системе Linux:

<VirtualHost *:80>
    ServerAdmin webmaster@test.local
    ServerName test.local
    ServerAlias www.test.local
                DocumentRoot /home/almanex/projects/test.local/public_html/                 
                <Directory /home/almanex/projects/test.local/public_html/> 
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>         
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Внимание: Не забудьте заменить UNIX имя пользователя (username) на свое (Шаг: 7), в моем случае это almanex.

Содержимое файла test.com.conf после правок для Wsl 2

Содержимое файла test.com.conf после правок для Wsl 1 и Wsl 2, где файлы  проекта находятся на диске файловой системы Windows —  C, D, E:

<VirtualHost *:80>
    ServerAdmin webmaster@test.local
    ServerName test.local
    ServerAlias www.test.local
                DocumentRoot /mnt/c/projects/test.local/public_html/
               <Directory /mnt/c/projects/test.local/public_html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>         
                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Внимание: Не забудьте заменить букву диска! В примере мы используем диск С.

Содержимое файла test.com.conf после правок для Wsl 1

Шаг 31: После внесения правок сохраните и закройте файл сочетанием клавиш CTRL X. Подтвердите операцию клавишей Y и нажмите ENTER.

Шаг 32: Включим новый виртуальный хост с помощью утилиты a2ensite:

sudo a2ensite test.local.conf

Шаг 33: Далее деактивируем сайт по умолчанию 000-default.conf:

sudo a2dissite 000-default.conf

Шаг 34: Перезапустим service apache:

sudo service apache2 restart

Wsl 2 Перезапустим service apache:

Перенаправление test.local на локальный веб-сервер.

Ваш проект доступен по адресу http://localhost/

Для того чтобы доменное имя http://test.local было связано с вашим локальным веб-сервером, откройте файл hosts, расположенный по адресу C:WindowsSystem32driversetc и добавить в него строки:

127.0.0.1 test.local

172.30.69.65 test.local

Чтобы определить ip-адрес вашего сетевого интерфейса (в моем случае это 172.30.69.65) можно использовать команду ip address в терминале (см. картинку ниже).

Чтобы определить ip-адрес вашего сетевого интерфейса используйте команду ip address

Команды для запуска и остановки веб-сервера.

Все, теперь перед началом работы с вашим веб проектом, вам нужно запустить Apache и MySQL, для этого необходимо ввести следующие команды по очереди:

sudo service apache2 start
sudo service mysql start

Для остановки веб-сервера:

sudo service apache2 stop
sudo service mysql stop

Необязательно: Чтобы было проще запускать и останавливать веб-сервер вы можете создать bash скрипты start.sh и stop.sh.

тобы было проще запускать и останавливать веб-сервер вы можете создать bash скрипты start.sh и stop.sh.

Как создать скрипт start.sh:

Шаг 1: Откройте терминал и создайте файл командой:

sudo nano ./start.sh

Шаг 2: Вставьте следующее содержимое, где замените password на пароль, который установили для пользователя Ubuntu:

#!/bin/bash

echo password | sudo -S sudo service apache2 start

echo password | sudo -S sudo service mysql start

exit 0

wsl2 замените password на пароль, который установили для пользователя Ubuntu

Шаг 3: Необходимо отредактировать права доступа для start.sh. Выполните команду:

sudo chmod -R 755 ./start.sh

Скрипт stop.sh:

Шаг 4: Создайте файл командой:

sudo nano ./stop.sh

Содержимое файла stop.sh:

#!/bin/bash

echo password | sudo -S sudo service apache2 stop

echo password | sudo -S sudo service mysql stop

exit 0

Шаг 5: Отредактировать права доступа:

sudo chmod -R 755 ./stop.sh

Проверка работоспособности веб-сервера.

Для проверки работоспособности веб-сервера установим на test.local систему управления контентом, например, OctoberCMS, MODX Revolution или WordPress.

Для этого скачаем с официальной страницы архив системы WordPress и распакуем его в созданную нами директорию

С:Projectstest.localpublic_html 

или

/home/main/projects/test.local/public_html

Для установки системы необходимо открыть мастер. Откроем в браузере адрес http://test.local. После этого ответим на все вопросы мастера и нажмём на кнопку «Вперед», введем сведения о подключении к базе данных testlocal и тд..

WordPress wsl Windows 10

Дождёмся окончания процесса установки. Готово!

Заключение

Теперь, когда ваш веб-сервер установлен и работает используя подсистему Wsl, у вас огромное количество вариантов того, что делать дальше. Вы установили платформу, которая позволит развернуть большинство типов веб-сайтов и сетевого программного обеспечения на вашем сервере. Дайте нам знать в комментариях ниже, помогло ли это руководство или есть какая-либо другая тема, которую вы хотели бы видеть.

Рекомендуем: Экспорт и импорт дистрибутива Linux WSL1 и WSL2 в Windows 10

This article explains how to install PHP 8.2 and Apache 2.4 on Windows 10 or 11 (64-bit).

Linux and macOS users often have Apache and PHP pre-installed or available via package managers. Windows requires a little more effort. The steps below may work with other editions of Windows, PHP, and Apache, but check the documentation of each dependency for specific instructions.

Contents:

  1. Why PHP?
  2. Why Install PHP Locally?
  3. Alternative Installation Options
    • Using an all-in-one package
    • Using a Linux virtual machine
    • Using Windows Subsystem for Linux 2
    • Using Docker
  4. Installing Apache (optional)
  5. Installing PHP
    • Step 1: Download the PHP files
    • Step 2: Extract the files
    • Step 3: Configure php.ini
    • Step 4: Add C:php to the PATH environment variable
    • Step 5: Configure PHP as an Apache module
    • Step 6: Test a PHP file

Why PHP?

PHP remains the most widespread and popular server-side programming language on the Web. It’s installed by most web hosts, and has a simple learning curve, close ties with the MySQL database, superb documentation, and a wide collection of libraries to cut your development time. PHP may not be perfect, but you should consider it for your next web application. It’s the language of choice for Facebook, Slack, Wikipedia, MailChimp, Etsy, and WordPress (the content management system which powers almost 45% of the web).

To get your PHP setup blazing fast, check out our free book on improving PHP Performance.

Why Install PHP Locally?

Installing PHP on your development PC allows you to create and test websites and applications without affecting the data or systems on your live server.

Alternative Installation Options

Before you jump in, there may be a simpler installation options…

Using an all-in-one package

All-in-one packages are available for Windows. They contain Apache, PHP, MySQL, and other useful dependencies in a single installation file. These packages include XAMPP, WampServer and Web.Developer.

These packages are easy to use, but they may not match your live server environment. Installing Apache and PHP manually will help you learn more about the system and configuration options.

Using a Linux virtual machine

Microsoft Hyper-V (provided in Windows Professional) and VirtualBox are free hypervisors which emulate a PC so you can install another operating system.

You can install any version of Linux, then follow its Apache and PHP installation instructions. Alternatively, distros such as Ubuntu Server provide them as standard (although they may not be the latest editions).

Using Windows Subsystem for Linux 2

WSL2 is also a virtual machine, but it’s tightly integrated into Windows so activities such as file sharing and localhost resolution are seamless. You can install a variety of Linux distros, so refer to the appropriate Apache and PHP instructions.

Using Docker

Docker creates a wrapper (known as a container) around pre-configured application dependencies such as Apache, PHP, MySQL, MongoDB, and most other web software. Containers look like full Linux Virtual Machines but are considerably more lightweight.

Once you’ve installed Docker Desktop on Windows, it’s easy to download, configure, and run Apache and PHP.

Docker is currently considered the best option for setting up a PHP development environment. Check out SitePoint’s article Setting Up a Modern PHP Development Environment with Docker for a complete guide to setting it up.

Installing Apache (optional)

The following sections describe how to install Apache and PHP directly on Windows.

PHP provides a built-in web server, which you can launch by navigating to a folder and running the PHP executable with an -S parameter to set the localhost port. For example:

cd myproject
php -S localhost:8000

You can then view PHP pages in a browser at http://localhost:8000.

This may be adequate for quick tests, but your live server will use Apache or similar web server software. Emulating that environment as closely as possible permits more advanced customization and should prevent development errors.

To install Apache, download the latest Win64 ZIP file from https://www.apachelounge.com/download/ and extract its Apache24 folder to the root of your C: drive. You’ll also need to install the Visual C++ Redistributable for Visual Studio 2015–2020 (vc_redist_x64); the page has a link at the top.

Open a cmd command prompt (not PowerShell) and start Apache with:

cd C:Apache24bin
httpd

You may need to accept a firewall exception before the server starts to run. Open http://localhost in a browser and an “It works!” message should appear. Note:

  • C:Apache24confhttpd.conf is Apache’s configuration file if you need to change server settings.
  • C:Apache24htdocs is the web server’s root content folder. It contains a single index.html file with the “It works!” message.

If Apache fails to start, another application could be hogging port 80. (Skype is the prime candidate, and the Windows app won’t let you disable it!) If this occurs, edit C:Apache24confhttpd.conf and change the line Listen 80 to Listen 8080 or any other free port. Restart Apache and, from that point onward, you can load web files at http://localhost:8080.

Stop the server by pressing Ctrl + C in the cmd terminal. The ReadMe file in the ZIP also provides instructions for installing Apache as a Windows service so it auto-starts on boot.

Installing PHP

Install PHP by following the steps below. Note that there’s more than one way to configure Apache and PHP, but this is possibly the quickest method.

Step 1: Download the PHP files

Get the latest PHP x64 Thread Safe ZIP package from https://windows.php.net/download/.

Create a new php folder in the root of your C: drive and extract the content of the ZIP into it.

You can install PHP anywhere on your system, but you’ll need to change the paths referenced below if you use anything other than C:php.

Step 3: Configure php.ini

PHP’s configuration file is php.ini. This doesn’t exist initially, so copy C:phpphp.ini-development to C:phpphp.ini. This default configuration provides a development setup which reports all PHP errors and warnings.

You can edit php.ini in a text editor, and you may need to change lines such as those suggested below (use search to find the setting). In most cases, you’ll need to remove a leading semicolon (;) to uncomment a value.

First, enable any required extensions according to the libraries you want to use. The following extensions should be suitable for most applications including WordPress:

extension=curl
extension=gd
extension=mbstring
extension=pdo_mysql

If you want to send emails using PHP’s mail() function, enter the details of an SMTP server in the [mail function] section (your ISP’s settings should be suitable):

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = mail.myisp.com
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = my@emailaddress.com

Step 4: Add C:php to the PATH environment variable

To ensure Windows can find the PHP executable, you must add it to the PATH environment variable. Click the Windows Start button and type “environment”, then click Edit the system environment variables. Select the Advanced tab, and click the Environment Variables button.

Scroll down the System variables list and click Path, followed by the Edit button. Click New and add C:php.

PHP path environment variable

Note that older editions of Windows provide a single text box with paths separated by semi-colons (;).

Now OK your way out. You shouldn’t need to reboot, but you may need to close and restart any cmd terminals you have open.

Step 5: Configure PHP as an Apache module

Ensure Apache is not running and open its C:Apache24confhttpd.conf configuration file in a text editor. Add the following lines to the bottom of the file to set PHP as an Apache module (change the file locations if necessary but use forward slashes rather than Windows backslashes):

# PHP8 module
PHPIniDir "C:/php"
LoadModule php_module "C:/php/php8apache2_4.dll"
AddType application/x-httpd-php .php

Optionally, change the DirectoryIndex setting to use index.php as the default in preference to index.html. The initial setting is:

<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

Change it to:

<IfModule dir_module>
    DirectoryIndex index.php index.html
</IfModule>

Save httpd.conf and test the updates from a cmd command line:

cd C:Apache24bin
httpd -t

Syntax OK will appear … unless you have errors in your configuration.

If all went well, start Apache with httpd.

Step 6: Test a PHP file

Create a new file named index.php in Apache’s web page root folder at C:Apache24htdocs. Add the following PHP code:

<?php
phpinfo();
?>

Open a web browser and enter your server address: http://localhost/. A PHP version page should appear, showing all PHP and Apache configuration settings.

You can now create PHP sites and applications in any subfolder of C:Apache24htdocs. If you need to work more than one project, consider defining Apache Virtual Hosts so you can run separate codebases on different localhost subdomains or ports.

Further information:

  • How to Install Apache
  • How to Install MySQL
  • MySQL: the Pros and Cons of MyISAM Tables
  • MySQL: the Pros and Cons of InnoDB Tables
  • How to Use MySQL Foreign Keys for Quicker Database Development
  • Book: PHP & MySQL: Novice to Ninja, 7th Edition
  • Book: Jump Start PHP Environment, as well as many more books in our library.

Best of luck!

In this article, we will discuss “How to Setup Apache, PHP & MySql on Windows 10″.  When you are planning to install Apache, PHP & MySQL on Windows 10 machine, then We have two options to do this as given below:

  1. You can setup Xampp or Wamp server which enables all the feature as per our requirement.
  2. You can build your own fully functional Wamp server manually. In this, you have to install the Apache, MySql, and PHP manually.

I’m a Windows 10 user, so this tutorial is related to the Windows 10. Before starting the implementation, you need to read this article once.

Now, time to decide the versions we need to install. For this tutorial, I’m choosing the latest versions.

Setup Apache, PHP & MySql on Windows 10

Setup Apache

You can download the Apache server from the official site. Then extract the downloaded zip folder as per your desired location. Now follow the given instruction to install the Apache2.4 in windows 10.

Step 1: Open the command prompt as Administrator. And open the Apache root directory.

Setup Apache, PHP & MySql on Windows 10

Step 2: Time to update the “httpd.conf” config file located at “{Your directory path}/Apache24/conf”. Open the file and update the “SRVROOT”. I’m updating as per my directory setup.

Define SRVROOT "F:/localserver/Apache24"

Step 3: Setup the windows service. You can use the httpd -k install command to install the Apache2.4 service.Setup Apache, PHP & MySql on Windows 10

Step 4: After installing the service, you need to start the service. You can manage it from the windows service program. You need to open the “RUN” box using “Windows + R” key where you can type “services.msc” command to open the Service” program. Open the program and search Apache.

Setup Apache, PHP & MySql on Windows 10

After that click on the “start” then Apache service is started. You can stop or restart the service in the same place.

Setup Apache, PHP & MySql on Windows 10

Step 5: Time to test the Apache. Open the browser and hit the localhost in the URL.

Setup Apache, PHP & MySql on Windows 10


Setup PHP

Please download the latest PHP version from the official site. Then extract the downloaded zip folder as per your desired location. I recommend this to store PHP folder in the same location where you had setup the Apache Server. Now follow the given instruction to install the PHP and setup this with the Apache server.

Step 1: Rename php-ini-development.ini to php.ini.

Step 2: Add PHP in system environment variable using “setx path” command at command prompt.

C:>setx path "%PATH%, F:localserverphp-7.3.0" /M

Setup Apache, PHP & MySql on Windows 10

Step 3:  Update the “httpd.conf” config file once again. Open the file and append the following snippet.

// Update the PHP directory path as per your setup.
PHPIniDir "F:/localserver/PHP-7.3.0"
AddHandler application/x-httpd-php .php
LoadModule php7_module "F:/localserver/PHP-7.3.0/php7apache2_4.dll"

Step 4: Restart the “Apache2.4” service. After that create one testing PHP file under htdocs directory located at “{directory_path}/Apache24/”. Here I have created “phpinfo.php” page. At the end here the working PHP setup.

Setup Apache, PHP & MySql on Windows 10


Setup MySQL Server

You need to download the latest version of MySQL Server from the official site. I’m choosing an installer setup for my windows 10. After download completion, you need to follow the steps given below:

Step 1: Execute the installer, accept license agreement then click next.

MySql Server Setup Manually

Step 2: Select the setup type, I’m choosing a server only. You can choose “Developer Default”, this includes more tools like workbench, connectors and etc if required.

MySql Server Setup Manually

Step 3: In this step, we are checking requirements. Then click on the execute option.

MySql Server Setup Manually

Step 4: After completing the required setup. Popup is shown you need to click on the close button on a popup.

MySql Server Setup Manually

Step 5: After closing the popup, You have seen the green right tick on the requirement listed item. Just need to click on the next button.

MySql Server Setup Manually

Step 6: All is done now. Here you need to execute the setup.

MySql Server Setup Manually

Step 7: Again you have seen the green right tick symbol on the listed item. You need to click on the next button.

MySql Server Setup Manually

Step 8: Select the “Standalone MySQL Server” option. And click on the next button.

MySql Server Setup Manually

Step 9: Setup type and networking options. All details are predefined, you can change those as per your requirements.

MySql Server Setup Manually

Step 10: Select the authentication method, note that you need to use the legency authentication method. Because it will help you to setup this MySql Server with the phpmyadmin.

MySql Server Setup Manually

Step 11: Setup the root password.

MySql Server Setup Manually

Step 12: Here’s all the configuration step processed one by one. You need to click on the finish button when the process is done.

MySql Server Setup Manually

Step 13: Everythings done now, click the next button. And complete the final step.

MySql Server Setup Manually

MySQL server is ready now. You can manage MySQL service from the windows service program. You need to open the “RUN” box using “Windows + R” key where you can type “services.msc” command to open the Service” program. Open the program and search MySQL Service.

MySql Server Setup Manually


Setup phpMyAdmin

Our Apache and MySql setup are ready now. You need a client application to access the MySQL database such as MySQL Workbench, phpMyAdmin or etc. Now, we are going to setup the phpmyadmin with our MySql Server.

You can download the phpMyAdmin from the official site. Extract the downloaded zip file in “{directory_path}/Apache24/htdocs” and rename the folder to “phpmyadmin”.

After that, you need to update the “httpd.conf” located at “Apache24” directory. Open the file and update the ”dir_module”.

<IfModule dir_module>
    # Here you need to update index.html to index.php
    DirectoryIndex index.php
</IfModule>

Now, when you open a directory in the browser then the “index.php” file executes by default.

After that, you need to copy a file “config.sample.inc.php” located at “{directory_path}/Apache24/htdocs/phpmyadmin” and save this with a new name “config.inc.php” on the same location. Open the file and update the following code snippet.

/**
 * This is needed for cookie based authentication to encrypt password in
 * cookie. Needs to be 32 chars long.
 */
$cfg['blowfish_secret'] = 'n34uLaA3lvexVi6RaSG3T1BTna123m78'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */

/* Authentication type */
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here. here you need to add the password which you setup at the time of mysql server authentication setup.

Everything ready, Now time to check our phpmyadmin.

phpMyAdmin setup with MySql Server Manually

Conclusion

In this article, we are discussing the “Setup Apache, PHP & MySql on Windows 10”. We are creating this tutorial for knowledge. You can use Xampp or Wamp server, both of the servers provide rich features and flexibilities. Using these no need to install Apache, PHP, MySql or PHPMyAdmin manually. Please feel free to add the comment if any query or you can submit your feedback 🙂

If you like our content, please consider buying us a coffee.
Thank you for your support!

Buy Me a Coffee

Оглавление

1. Веб-сервер на Windows

2. Как установить Apache на Windows

3. Как установить PHP на Windows

4. Настройка PHP 8

5. Как установить MySQL в Windows

6. Как установить phpMyAdmin в Windows

Заключение


Веб-сервер — это программа, которая предназначена для обработки запросов к сайтам и отправки пользователям страниц веб-сайтов. Самый популярный пример веб-сервера это Apache.

PHP — это язык программирования. Также называется среда для выполнения скриптов, написанных на PHP. В операционной системе, в том числе и Windows, PHP может быть установлен самостоятельно, без веб-сервера. В этом случае программы (скрипты) на PHP можно запускать из командной строки. Но веб-приложения очень часто используют PHP, данный интерпретатор стал, фактически, стандартом веб-серверов и поэтому они почти всегда устанавливаются вместе.

MySQL — это система управления базами данных (СУБД). Это также самостоятельная программа, она используется для хранения данных, поиска по базам данных, для изменения и удаления данных. Веб-приложения нуждаются в постоянном хранилище, поэтому для веб-сервера дополнительно устанавливается и СУБД. Кстати, вполне возможно, что вы слышали про MariaDB — это тоже СУБД. Первой появилась MySQL, а затем от неё ответвилась MariaDB. Для веб-приложений обе эти СУБД являются взаимозаменяемыми, то есть никакой разницы нет. В этой инструкции я буду показывать установку на примере MySQL, тем не менее если вы хотите попробовать новую MariaDB, то смотрите статью «Инструкция по установке веб-сервера Apache c PHP, MariaDB и phpMyAdmin в Windows».

Что касается phpMyAdmin, то это просто скрипт на PHP, который предназначен для работы с базами данных — наглядно выводит их содержимое, позволяет выполнять в графическом интерфейсе такие задачи как создавать базы данных, создавать таблицы, добавлять, изменять и удалять информацию и т. д. По этой причине phpMyAdmin довольно популярен, хотя и не является обязательной частью веб-сервера.

Особенность Apache и других компонентов веб-сервера в том, что их корни уходят в Linux. И эти программы применяют в своей работе основные концепции этой операционной системы. Например, программы очень гибки в настройке — можно выполнить установку в любую папку, сайты также можно разместить в любой папке, в том числе на другом диске, не на том, где установлен сам веб-сервер. Даже файлы журналов можно вынести на третий диск и так далее. У веб-сервера много встроенных модулей — можно включить или отключить их в любом сочетании, можно подключить внешние модули. Можно создать много сайтов на одном веб-сервере и для каждого из них установить персональные настройки. Но эта гибкая настройка выполняется через текстовые файлы — именно такой подход (без графического интерфейса) позволяет описать любые конфигурации

Не нужно этого боятся — я расскажу, какие файлы нужно редактировать и что именно в них писать.

Мы не будем делать какие-то комплексные настройки — наша цель, просто установить веб-сервер на Windows. Тем не менее было бы странно совсем не использовать такую мощь в настройке. Мы разделим сервер на две директории: в первой будут исполнимые файлы, а во второй — данные (файлы сайтов и баз данных). В будущем, когда возникнет необходимость делать резервные копии информации или обновлять веб-сервер, вы поймёте, насколько удобен этот подход!

Мы установим сервер в отдельную директорию. Для этого в корне диска C: создайте каталог Server. В этом каталоге создайте 2 подкаталога: bin (для исполнимых файлов) и data (для сайтов и баз данных).

Перейдите в каталог data и там создайте подпапки DB (для баз данных) и htdocs (для сайтов).

Перейдите в каталог C:ServerdataDB и создайте там пустую папку data.

Для работы всех компонентов веб-сервера необходим файл «Visual C++ Redistributable for Visual Studio 2015-2022» — это официальный файл от Microsoft. Чтобы его скачать перейдите по ссылке. После скачивания, запустите этот файл и выполните установку.

Подготовительные действия закончены, переходим к установке компонентов веб-сервера.

Как установить Apache на Windows

Перейдите на сайт apachelounge.com/download и скачайте .zip архив с веб-сервером:

Распакуйте папку Apache24 из этого архива в C:Serverbin.

Перейдите в каталог C:ServerbinApache24conf и откройте файл httpd.conf любым текстовым редактором.

В нём нам нужно заменить ряд строк.

Меняем

Define SRVROOT "c:/Apache24"

на

Define SRVROOT "c:/Server/bin/Apache24"

меняем

#ServerName www.example.com:80

на

ServerName localhost

меняем

DocumentRoot "${SRVROOT}/htdocs"
<Directory "${SRVROOT}/htdocs">

на

DocumentRoot "c:/Server/data/htdocs"
<Directory "c:/Server/data/htdocs">

меняем

DirectoryIndex index.html

на

DirectoryIndex index.php index.html index.htm

меняем

    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride None

на

    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

и меняем

#LoadModule rewrite_module modules/mod_rewrite.so

на

LoadModule rewrite_module modules/mod_rewrite.so

Сохраняем и закрываем файл. Всё, настройка Apache завершена! Описание каждой изменённой директивы вы найдёте на этой странице.

Откройте командную строку (это можно сделать нажав одновременно клавиши Win+x).

Выберите там Windows PowerShell (администратор) и скопируйте туда:

c:ServerbinApache24binhttpd.exe -k install

Если поступит запрос от файервола в отношение Apache, то нажмите Разрешить доступ.

Теперь вводим в командную строку:

c:ServerbinApache24binhttpd.exe -k start

И нажмите Enter.

Теперь в браузере набираем http://localhost/ и видим следующее:

Это означает, что веб-сервер работает. Чтобы увидеть там файлы, добавьте их в каталог c:Serverdatahtdocs — это главная папка для данных сервера, где будут размещаться все сайты.

Как установить PHP на Windows

PHP 8 скачайте со страницы windows.php.net/download/. Выберите версию Thread Safe, обратите внимание на битность. Если вы затрудняетесь, какой именно файл скачать, то посмотрите эту заметку.

В папке c:Serverbin создаём каталог PHP и копируем в него содержимое только что скаченного архива.

В файле c:ServerbinApache24confhttpd.conf в самый конец добавляем строчки:

PHPIniDir "C:/Server/bin/PHP"
AddHandler application/x-httpd-php .php
LoadModule php_module "C:/Server/bin/php/php8apache2_4.dll"

И перезапускаем Apache:

c:ServerbinApache24binhttpd.exe -k restart

В каталоге c:Serverdatahtdocs создаём файл с названием i.php, копируем в этот файл:

<?php
phpinfo ();

В браузере откройте ссылку http://localhost/i.php. Если вы видите что-то похожее, значит PHP работает:

Настройка PHP 8

Настройка PHP происходит в файле php.ini. В zip-архивах, предназначенных для ручной установки и для обновлений, php.ini нет (это сделано специально, чтобы при обновлении случайно не удалить ваш файл с настройками). Зато есть два других, которые называются php.ini-development и php.ini-production. Любой из них, при ручной установке, можно переименовать в php.ini и настраивать дальше. На локалхосте мы будем использовать php.ini-development.

Открываем файл php.ini любым текстовым редактором, ищем строчку

;extension_dir = "ext"

и заменяем её на

extension_dir = "C:ServerbinPHPext"

Теперь найдите группу строк:

;extension=bz2
;extension=curl
;extension=ffi
;extension=ftp
;extension=fileinfo
;extension=gd
;extension=gettext
;extension=gmp
;extension=intl
;extension=imap
;extension=ldap
;extension=mbstring
;extension=exif      ; Must be after mbstring as it depends on it
;extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
;extension=odbc
;extension=openssl
;extension=pdo_firebird
;extension=pdo_mysql
;extension=pdo_oci
;extension=pdo_odbc
;extension=pdo_pgsql
;extension=pdo_sqlite
;extension=pgsql
;extension=shmop

и замените её на:

extension=bz2
extension=curl
extension=ffi
extension=ftp
extension=fileinfo
extension=gd
extension=gettext
extension=gmp
extension=intl
extension=imap
extension=ldap
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
;extension=oci8_12c  ; Use with Oracle Database 12c Instant Client
extension=odbc
extension=openssl
;extension=pdo_firebird
extension=pdo_mysql
;extension=pdo_oci
extension=pdo_odbc
extension=pdo_pgsql
extension=pdo_sqlite
extension=pgsql
extension=shmop

теперь раскомментируйте эту группу строк:

;extension=soap
;extension=sockets
;extension=sodium
;extension=sqlite3
;extension=tidy
;extension=xsl

должно получиться:

extension=soap
extension=sockets
extension=sodium
extension=sqlite3
extension=tidy
extension=xsl

Этими действиями мы включили расширения. Они могут понадобиться в разных ситуациях для разных скриптов. Сохраняем файл и перезапускаем Apache.

c:ServerbinApache24binhttpd.exe -k restart

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

Также рекомендуется ознакомиться со статьями Что делать если PHP скрипту не хватает времени и памяти. Почему большой файл не загружается на сайт или в phpMyAdmin и Как увеличить память и время для PHP скриптов.

Материалы по дополнительной настройке, в том числе подключение поддержки PERL, Ruby, Python в Apache (только для тех, кому это нужно):

  • Как тестировать отправку писем в PHP на Windows
  • Настройка веб-сервера Apache для запуска программ Ruby на Windows
  • Настройка веб-сервера Apache для запуска программ Perl на Windows
  • Как настроить веб-сервер Apache на запуск Python в Windows

Как установить MySQL в Windows

Бесплатная версия MySQL называется MySQL Community Server. Её можно скачать на странице https://dev.mysql.com/downloads/mysql/. На этой же странице есть установщик в виде исполнимого файла, но я рекомендую скачать ZIP-архив.

На странице скачивания нам предлагают зарегистрироваться или войти в существующую учётную запись — но это делать необязательно. Достаточно нажать на ссылку «No thanks, just start my download».

В каталог c:Serverbin распаковываем файлы из только что скаченного архива. Распакованная папка будет называться примерно mysql-8.0.17-winx64 (зависит от версии), переименуйте её в mysql-8.0.

Заходим в эту папку и создаём там файл my.ini. Теперь открываем этот файл любым текстовым редактором и добавьте туда следующие строки:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
datadir="c:/Server/data/DB/data/"
default_authentication_plugin=mysql_native_password

Сохраните и закройте его.

Настройка завершена, но нужно ещё выполнить инициализацию и установку, для этого открываем командную строку от имени администратора и последовательно вводим туда:

C:Serverbinmysql-8.0binmysqld --initialize-insecure --user=root
C:Serverbinmysql-8.0binmysqld --install
net start mysql

По окончанию этого процесса в каталоге C:ServerdataDBdata должны появиться автоматически сгенерированные файлы.

Теперь служба MySQL будет запускаться при каждом запуске Windows.

Как установить phpMyAdmin в Windows

Сайт для скачивания phpMyAdmin: phpmyadmin.net.

Прямая ссылка на самую последнюю версию: phpMyAdmin-latest-all-languages.zip.

В каталог c:Serverdatahtdocs копируем содержимое только что скаченного архива. Переименовываем эту папку в phpmyadmin.

В каталоге c:Serverdatahtdocsphpmyadmin создаём файл config.inc.php и копируем туда:

<?php
 
/* Servers configuration */
$i = 0;
 
/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = '';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['nopassword'] = true;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
 
/* End of servers configuration */
 
$cfg['blowfish_secret'] = 'kjLGJ8g;Hj3mlHy+Gd~FE3mN{gIATs^1lX+T=KVYv{ubK*U0V';
$cfg['DefaultLang'] = 'ru';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
 
?>

В браузере набираем http://localhost/phpmyadmin/

В качестве имя пользователя вводим root. Поле пароля оставляем пустым.

Заключение

Вот и всё — теперь у вас есть свой персональный локальный веб-сервер на своём домашнем компьютере.

Если вдруг у вас что-то не получилось, то скорее всего вы пропустили какой-то шаг или сделали его неправильно — попробуйте всё сделать в точности по инструкции. Если проблема осталась, то ознакомьтесь со справочным материалом «Ошибки при настройке и установке Apache, PHP, MySQL/MariaDB, phpMyAdmin» и если даже он не помог, то напишите о своей ошибке в комментарии.

Большое количество материалов по Apache на русском языке специально для Windows вы найдёте на этой странице.

Примеры материалов, которые могут вам пригодиться в первую очередь:

  • Как защитить веб-сервер Apache от взлома в Windows
  • Несколько сайтов на Apache
  • Apache Forwarding — проброска портов веб-сервера
  • Как сделать резервную копию баз данных MySQL (MariaDB) в Windows без phpMyAdmin
  • Почему в логах ошибок Apache не сохраняются записи об ошибке 404
  • Как в Windows поменять сообщения ошибок Apache
  • Как настроить PHP для работы с get_browser (browscap.ini) в Windows
  • Файл .htaccess в Apache
  • Как обновить Apache на Windows
  • Как обновить PHP
  • Как обновить MySQL
  • Как обновить phpMyAdmin

Связанные статьи:

  • Ошибки при настройке и установке Apache, PHP, MySQL/MariaDB, phpMyAdmin (97.9%)
  • Установка Apache, PHP, MySQL и phpMyAdmin на Windows XP (60.4%)
  • Готовая сборка Apache для Windows XP (60.4%)
  • Что делать если PHP скрипту не хватает времени и памяти. Почему большой файл не загружается на сайт или в phpMyAdmin (58.4%)
  • Ошибка «Composer detected issues in your platform: Your Composer dependencies require the following PHP extensions to be installed: mysqli, openssl» (РЕШЕНО) (58.4%)
  • Как подключить PHP к Apache на Windows (RANDOM — 53.1%)

Понравилась статья? Поделить с друзьями:
  • Как раздать интернет с компьютера на компьютер windows 10
  • Как разгрузить процессор windows 10 для игр
  • Как развернуть ntp сервер на windows 10
  • Как раздать интернет с компьютера без роутера на windows 7
  • Как разгрузить память на windows 10 в диспетчере задач