Руководство по ручной установке
Этот раздел содержит инструкции для ручной установки и настройки PHP на Microsoft Windows.
Выбор и загрузка пакета дистрибутивов PHP
Если PHP используется с IIS, тогда следует использовать PHP 5.3 VC9 Non Thread Safe или PHP 5.2 VC6 Non Thread Safe;
Если PHP используется с IIS7 или выше и версия PHP 5.3+, тогда должна использоваться версия дистрибутива PHP VC9.
Если PHP используется с Apache 1 или Apache 2 тогда выбирайте PHP 5.3 VC6 или PHP 5.2 VC6.
Замечание:
Версии VC9 компилируются с помощью Visual Studio 2008 и имеют улучшенную производительность и стабильность. Версии VC9 требуют наличия в системе » Microsoft 2008 C++ Runtime (x86) или » Microsoft 2008 C++ Runtime (x64).
Структура пакетов PHP и их содержимое
Распакуйте содержимое zip архива в директорию по вашему выбору, например C:\PHP\. Директория и структура файлов, извлеченных из zip, будет такой:
Пример #1 Структура пакета PHP 5
go-pear.bat — скрипт установки PEAR. Подробнее см. » Установка (PEAR).
php-cgi.exe — исполняемый файл CGI, который может быть использован во время запуска PHP на IIS через CGI или FastCGI.
php-win.exe — исполняемый файл PHP для выполнения PHP скриптов без использования консоли (например, приложения PHP, использующие Windows GUI).
php.exe — исполняемый файл PHP для выполнения PHP скриптов в консоли (CLI).
php5apache2_2.dll — модуль Apache 2.2.X.
php5apache2_2_filter.dll — фильтр Apache 2.2.X.
Изменение файла php.ini
После того, как содержимое пакета php извлечено, создайте копию php.ini-production с именем php.ini в той же папке. Если необходимо, также возможно разместить php.ini в любом другом месте по вашему выбору, но это потребует дополнительной настройки, которая приводится в разделе Настройка PHP.
Файл php.ini содержит правила исполнения PHP и инструкции по работе с окружением, в котором он запускается. Ниже приводятся некоторые из настроек php.ini , которые могут улучшить работу PHP в Windows. Некоторые из них опциональны. Есть много других директив, которые могут быть полезны в вашем окружении — обращайтесь к списку директив php.ini за более подробной информацией.
extension_dir = <путь к директории расширений> — extension_dir указывает директорию, где расположены расширения PHP. Путь может быть абсолютным (например "C:\PHP\ext") или относительным (например ".\ext"). Используемые в php.ini расширения должны быть расположены в extension_dir .
extension = xxxxx.dll — Для каждого подключаемого расширения необходимо указать директиву "extension=". Расширения из extension_dir , отмеченные такой директивой, загружаются при старте PHP.
log_errors = On — в PHP есть механизм ведения лога ошибок, который может использоваться для сохранения ошибок в файле или для отправки в сервис (например syslog). Механизм также использует значение директивы error_log . Когда PHP исполняется службой IIS, log_errors должен быть включен с корректным error_log .
error_log = <пусть к файлу лога ошибок> — error_log нужен для обозначения абсолютного или относительного пути к файлу, в который протоколируются ошибки PHP. Этот файл должен доступным для записи веб-сервером. Самые распространенные места размещения этого файла — различные временные TEMP директории, например "C:\inetpub\temp\php-errors.log".
cgi.force_redirect = 0 — Эта директива необходима для исполнения под IIS. Это механизм защиты директории, требуемый многими другими веб серверами. Однако, включение его под IIS вызовет ошибки ядра PHP в Windows.
cgi.fix_pathinfo = 1 — Обеспечивает поддержку PATH_INFO согласно спецификации CGI. IIS FastCGI использует эту настройку.
fastcgi.impersonate = 1 — FastCGI под IIS поддерживает способность идентифицировать маркеры безопасности вызывающего клиента. Это позволяет IIS определять контекст безопасности, под которые выполняется запрос.
fastcgi.logging = 0 — Запись логов FastCGI должна быть выключена в IIS. Если запись включена, тогда все сообщения любых классов распознаются FastCGI как ошибки, что приведет IIS к генерации исключения HTTP 500.
max_execution_time = ## — Эта директива указывает максимальное время выполнения любого скрипта PHP. По умолчанию равно 30 секундам. Следует увеличить это значение, если приложение PHP должно выполняться дольше.
memory_limit = ###M — Количество памяти, доступное процессу PHP, в Мб. По умолчанию 128, что достаточно для большинства PHP приложений. Некоторым сложным приложениям может потребоваться больше памяти.
display_errors = Off — Директива определяет, какие ошибки следует возвращать веб-серверу для дальнейшего протоколирования. При значении "On" PHP сообщает обо всех видах ошибок, которые приводятся в директиве error_reporting . По соображениям безопасности рекомендуется установить в "Off" на рабочих серверах, чтобы исключить передачу вывода ошибок конечному пользователю, так как они могут содержат информацию, угрожающую безопасности приложения.
open_basedir = <пути к директориям, разделенные точкой с запятой>, например openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". Эта директива указывает пути к директориям, в которых PHP разрешены операции с файловой системой. Любая операция с файлами и директориями вне указанных путей будет приводить к ошибке. Эта директива особенно полезна для предотвращения доступа к установленному PHP в окружениях разделяемых хостингов для предотвращения доступа PHP скриптов к любым файлам вне корневой директории веб сайта.
upload_max_filesize = ###M и post_max_size = ###M — Максимальный разрешенный размер загруженного файла и присланных данных соответственно. Значения этих директив должны быть увеличены, если приложения PHP должны обрабатывать большие загружаемые файлы, например изображения или видеофайлы.
После установки PHP в вашей системе, следующим шагом будет выбор веб-сервера и его дальнейшая настройка для работы с PHP. Выберите конкретный веб-сервер в оглавлении к данному материалу.
Помимо запуска PHP с помощью веб-сервера, PHP может быть запущен из командной строки как .BAT скрипт. За более подробной информацией обращайтесь к материалу Консоль PHP на Microsoft Windows.
Как запустить php на windows
Этот раздел содержит примечания и подсказки, относящиеся к запуску PHP из командной строки для Windows.
Запуск PHP из командной строки можно выполнить без внесения каких-либо изменений в Windows.
Но есть несколько шагов, которые помогут упростить этот процесс. Некоторые из этих шагов уже должны были быть предприняты, но они повторяются здесь, чтобы иметь возможность предоставить полную пошаговую последовательность.
Замечание:
И PATH , и PATHEXT являются важными переменными, изначально существовавшими в Windows, и следует позаботиться о том, чтобы не перезаписывать ни одну из переменных, а только добавлять к ним.
Добавьте расположение исполняемого файла PHP ( php.exe , php-win.exe или php-cli.exe в зависимости от вашей версии PHP и предпочтений отображения) в переменную окружения PATH . Подробнее о том, как добавить каталог PHP в PATH , читайте в соответствующей записи часто задаваемых вопросов.
Добавьте расширение .PHP к переменной окружения PATHEXT . Это можно сделать одновременно с изменением переменной окружения PATH . Выполните те же действия, что и в ЧАВО, но измените переменную окружения PATHEXT , а не PATH .
Замечание:
Позиция, в которую вы помещаете .PHP , будет определять, какой скрипт или программа будет выполняться при совпадении имён файлов. Например, размещение .PHP перед .BAT приведёт к запуску вашего скрипта, а не пакетного файла, если существует пакетный файл с тем же именем.
Свяжите расширение .PHP с типом файла. Это делается с помощью следующей команды:
Свяжите тип файла phpfile с соответствующим исполняемым файлом PHP. Это делается с помощью следующей команды:
Выполнение этих шагов позволит запускать скрипты PHP из любого каталога без необходимости вводить исполняемый файл PHP или расширение .PHP , и все параметры будут переданы скрипту для обработки.
В приведённом ниже примере описаны подробности о некоторых изменениях в реестре, которые можно сделать вручную.
Пример #1 Изменения в реестре
С этими изменениями эту же команду можно записать как:
Замечание:
Есть небольшая проблема, если вы собираетесь использовать эту технику и использовать свои скрипты PHP в качестве фильтра командной строки, как в примере ниже:
Дополнительную информацию по этой проблеме можно найти в этой » статье базы знаний Microsoft : 321788. В Windows 10 этот параметр изменён на противоположный, и стандартная установка Windows 10 поддерживает унаследованные дескрипторы консоли. Это » сообщение на форуме Microsoft предоставляет объяснение.
How to Install PHP on Windows
![]()
Sajal Soni Last updated Jul 16, 2020
In this article, we’re going to discuss how to install PHP on Windows. There are three different ways to install and run PHP on Windows, and we’ll look at each one.
PHP is a server-side scripting language which is mostly used to build web applications—these may range from a very simple blog website to a full-fledged eCommerce store. In fact, PHP is one of the most popular server-side scripting languages for web development.
In the next section, we’ll go through the prerequisites for installing PHP on your Windows computer.
Prerequisites
Before we install PHP, let’s make sure of the following things.
The first thing to check is the Windows version. If you’re using a Windows version older than Windows 2008/Vista, you won’t be able to install PHP versions that are greater than 5.5. As per the official documentation, as of the PHP 7.2.0 version, Windows 2008 and Windows Vista are not supported.
Thus, it’s important to be sure that your Windows version aligns with the PHP version you want to install.
In the next section, we’ll discuss different ways to install PHP. If you want to install PHP manually, you should be comfortable editing a few system files since that is part of the manual installation process. On the other hand, if you just use the all-in-one package, it will be pretty straightforward, and all the configuration will happen automatically.
Today, we’re going to install the latest stable version of PHP, which is 7.4. In fact, PHP has several different versions, and if you want to install a different version of PHP and are facing any difficulties, drop me a line in the comments section and I’ll be happy to help.
With that out of the way, let’s get started installing PHP!
Possible Ways to Install PHP on Windows
In this section, I’ll briefly discuss the different ways you can install PHP on Windows.
Manual Installation
In the manual installation process, apart from downloading the PHP package, you need to go through a couple of steps to properly configure it. As I said earlier, if you prefer manual installation, you should be comfortable enough to edit a few configuration files in the text editor.
All-in-One Packages
There are a couple of popular Windows PHP distributions that come as all-in-one packages. Apart from PHP, these also install and configure the Apache web server and a MySQL database server. These packages are really useful for developers who want to set up and run the full web development stack quickly and easily.
XAMPP and WampServer are two of the most popular Windows distributions among the PHP community.
Using a .msi Installer
I would say this was one of the easiest and most preferred ways to install PHP among newbies. But it’s deprecated and not recommended anymore. To install PHP with an installer, you just need to download the .msi installer and run it to install PHP just like any other software you install on Windows.
However, as of PHP 5.4.0, you won’t find the .msi installer files on the PHP downloads page. So this is only going to be useful if you want to install an older PHP version. As it’s deprecated, we won’t discuss this installation method in detail.
How to Install PHP on Windows Manually
In this section, we’ll go through the steps that are required in order to install PHP in your Windows installation manually.
Download and Extract the PHP Package Files
The first thing you have to do is to download the PHP package file of your choice from the official PHP downloads page.
You’ll find .zip files available for both x86 and x64 systems, so make sure to download the correct one as per your Windows OS architecture. Also, you’ll have to choose either to download the non-thread-safe or thread-safe version of PHP. If you’re planning to run PHP as an Apache module, the thread-safe version is recommended. However, if you want to run PHP as a CGI module, you can choose either of them!
Next, you need to extract the .zip file in the directory where you want to install PHP. A common install location is C:\php. Create the php directory and extract the .zip file contents inside the C:\php directory.
Configure the php.ini Configuration File
In this section, we’ll discuss the necessary changes you need to make in the php.ini configuration file.
The PHP package that you’ve just downloaded already contains two different versions of the configuration file: php.ini-development and php.ini-production. The php.ini-development file is designed and configured for your local development. This has a lot of features enabled which make it easier to test and debug your code, but it makes your software run slower and is not secure for a live site. On the other hand, the php.ini-production file is designed for optimum performance and security. We’re going to use the php.ini-production file.
As PHP detects the php.ini file as its configuration file, you’ll have to copy the file which you choose for your local development, and rename it to the php.ini file. As we’re going to use the production version, copy the php.ini-production file to the C:\php\php.ini file.
Next, open the php.ini file in your favorite text editor and find the following line.
It’s the path of the PHP extensions directory, and let’s change it as shown in the following snippet.
It’s important to note that we’ve also removed the semicolon in front of the line to make sure it’s not commented. Of course, you need to adjust the above path to match your installation directory.
And with that, we’ve finished the php.ini configuration file changes.
Configure the PATH Environment Variable
In this final section, we’ll see how to add the PHP installation path to the PATH environment variable. The process of updating the PATH variable in Windows changes from version to version. I’ll show you how to change it in Windows 10, but feel free to ask me if you’re using a different version.
In the Windows search bar, just type the environment keyword and choose Edit the system environment variables in the search results. Go to the Advanced > Environment Variables section. Edit the PATH environment variable and add ;C:\php to the end. This will make it so you can run PHP just by typing php from the command prompt, no matter what folder you’re in.
Finally, reboot the system, and you’re done. You’ve successfully installed PHP in your Windows installation!
Installing With an All-in-One Package
As I mentioned earlier, XAMPP and WampServer are popular all-in-one packages that allow you to install PHP along with the other essential web development components like a web server and database server.
Irrespective of the tool you choose, the process of installing these tools is pretty straightforward. You just need to download the corresponding installer and run it to install it in your Windows installation. We won’t go into the details of this, but if you have any queries regarding this, feel free to post them.
In the next section, we’ll see how to enable specific PHP extensions in your PHP installation.
How to Install PHP Extensions
In this section, we’ll see how to enable PHP extensions.
Every time you want to enable a specific extension in PHP, you just need to find the associated entry in the php.ini configuration file and uncomment it.
For example, let’s say you want to enable the mysqli extension. Then you need to search for the extension=mysqli entry in the php.ini file and uncomment it, as shown in the following snippet.
In the same way, you can enable other extensions as well.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!

In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP).
Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.