- Установка в системах Windows
- Содержание
- User Contributed Notes 12 notes
- PHP на Windows и IIS7
- Установка и настройка PHP для использования с модулем FastCGI.
- Установка и настройка модуля FastCGI на IIS7.
- Рекомендации по настройке PHP на IIS7
- Частота перезапуска процессов PHP
- Использование нескольких версий PHP
- Общие инструкции по установке
Установка в системах Windows
Содержание
Установка PHP в современных операционных системах Microsoft Windows и рекомендуемая конфигурация под распространённые веб-серверы.
Если вы ищете информацию о старых версиях операционных систем: Windows XP, 2003, 98 или Apache 1.x, обратитесь к разделу руководства Установка на старых версиях ОС Windows.
Официальные релизы PHP для Windows рекомендованы для использования в промышленной эксплуатации. Однако, вы также можете собрать PHP из исходных кодов. Вам потребуется окружение Visual Studio. Обратитесь к разделу » Пошаговое руководство по сборке для получения более полной информации.
Установка PHP на Azure App Services (он же Microsoft Azure, Windows Azure, или (Windows) Azure Web Apps).
User Contributed Notes 12 notes
If you make changes to your PHP.ini file, consider the following.
(I’m running IIS5 on W2K server. I don’t know about 2K3)
PHP will not «take» the changes until the webserver is restarted, and that doesn’t mean through the MMC. Usually folks just reboot. But you can also use the following commands, for a much faster «turnaround». At a command line prompt, type:
and that will stop the webserver service. Then type:
net start w3svc
and that will start the webserver service again. MUCH faster than a reboot, and you can check your changes faster as a result with the old:
in your page somewhere.
I wish I could remember where I read this tip; it isn’t anything I came up with.
You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I’ve seen so far, limited to reconfiguring Apache’s httpd.conf.
My goal is to have PHP5 as the default scripting language for .php files in my DocumentRoot (which is in my case d:/htdocs), and PHP4 for specified DocumentRoot subdirectories.
Here it is (Apache’s httpd.conf contents):
—————————
# replace with your PHP4 directory
ScriptAlias /php4/ «c:/usr/php4/»
# replace with your PHP5 directory
ScriptAlias /php5/ «c:/usr/php5/»
AddType application/x-httpd-php .php
Action application/x-httpd-php «/php5/php-cgi.exe»
# populate this for every directory with PHP4 code
Action application/x-httpd-php «/php4/php.exe»
# directory where your PHP4 php.ini file is located at
SetEnv PHPRC «c:/usr/php4»
# remember to put this section below the above
# directory where your PHP5 php.ini file is located at
SetEnv PHPRC «c:/usr/php5»
—————————
This solution is not limited to having only two parallel versions of PHP. You can play with httpd.conf contents to have as many PHP versions configured as you want.
You can also use multiple php.ini configuration files for the same PHP version (but for different DocumentRoot subfolders), which might be useful in some cases.
Remember to put your php.ini files in directories specified in lines «SetEnv PHPRC. «, and make sure that there’s no php.ini files in other directories (such as c:\windows in Windows).
And finally, as you can see, I run PHP in CGI mode. This has its advantages and limitations. If you have to run PHP as Apache module, then. sorry — you have to use other solution (the best advice as always is: Google it!).
Hope this helps someone.
If you are installing PHP on Vista just go to David Wang’s blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx
I made the mistake of setting a ‘wildcard application map’ for PHP on a Windows 2003 / IIS 6.0 / PHP ISAPI installation.
This resulted in «No input file specified» errors whenever I tried to load the default page in my site’s directories. I don’t know why this broke things, but it did.
If anyone has the same problem, this may be the cause.
IIS setup: 403 forbidden error.
We had installed two separate different PHP versions — PHP 5.1.4 followed by 5.2.5.
We configured 5.2.5 php5isapi.dll to be loaded as the .php file type extension.
Despite this, php version 5.1.4 was being loaded. We renamed 5.1.4’s folder and then PHP was not loading at all.
There were no visible references to 5.1.4 in the IIS configuration, but in the file \webConfig.xml, there was a reference to 5.1.4’s isapi under IISFilters.
To fix this problem, we added version 5.2.5’s php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.
I installed by Microsoft Installer, manually, whatever I always received de same error from IIS7.
HTTP Error 404.3 — Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
The IIS7 interface is quite diferent and are not all together like IIS6
The 5.3 version have not any of those files: php5stdll, php5isapi.dll. etc.
The installer puts others files in handlers and I decided to use them as substitutes. Nothing done!
After that, I discovered that installer do not install these files within the sites, but in the root default site configuration of IIS7.
So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)
If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN
There is a .ini file there that prevents some files from being served by IIS, even if they exist, instead IIS will give a 404. The urlscan logfile (same place) should give you some insight into what parameter is preventing a page from loading, if any.
Here’s how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:
1. Right-click My Computer, go to Advanced tab, and click on Environment Variables.
Add the two installations and their EXT directories to the Path variable. For example, add:
c:\php;c:\php\ext;c:\TMAS\php;c:\tmas\php\ext;
Then, add the newer PHP version’s directory as a variable called PHPRC. For example:
Variable:PHPRC
Value: C:\PHP
Click OK to close the Environment Variables window, and click OK to close System Properties.
2. In registry, under HKEY_LOCAL_MACHINE>SOFTWARE>PHP, add a REG_SZ key called iniFilePath and give it a value
of the directory where the older PHP is installed. For example:
C:\TMAS\PHP
3. In IIS, go to the Web Service Extensions. Add both versions’ ISAPI module separately to the extensions
list, and allow both.
4. In IIS, go to each website utilizing the PHP versions. Set an ISAPI filter if needed. On the Home Directory
tab, click Configuration, and add .php, .php3, .phtml, and any other extensions needed (perhaps .html?) to
be filtered through PHP, and specify the ISAPI module version needed for each website.
You can now run two versions of PHP. This is because the order of where to look for the .ini file changed
between previous PHP versions and PHP 5.2, as documented at http://us2.php.net/ini:
* SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
* The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
* HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
* Current working directory (for CLI)
* The web server’s directory (for SAPI modules), or directory of PHP (otherwise in Windows)
* Windows directory (C:\windows or C:\winnt) (for Windows), or —with-config-file-path compile time option
—————————————————-
PHP 5.2.9.2 Install on XP Pro IIS 5.1 — phpinfo( ) results incorrect
Testing Date: 05.15.09
Background:
For several days now I, as a newbie, have been unsure if I had installed PHP correctly, or not. No matter what I did phpinfo( ) reported «Configuratin File Path» as: “C:\WINDOWS”. I was left to wonder what was wrong.
To help resolve the phpinfo() “issue”, I conducted a series of tests using two scripts:
The first is “test-php-ini-loaded.php”; it is stored in c:\inetpub\wwwroot, and has the following code:
if ( $inipath ) <
echo ‘Loaded php.ini: ‘ . $inipath ;
> else <
echo ‘A php.ini file is not loaded’ ;
>
?>
The second script is simply calls phpinfo( ). It is named test.php, is stored in “c:\inetpub\wwroot”, and has the following code:
( ); ?>
My Dev Environment:
1. Windows XP Pro SP3
2. IIS 5.1 / MMC 3.0
3. PHP 5.2.9.2 – phpMyAdmin not yet installed
4. (plus MySQL 5.1, etc.)
5. Install location is on my local E: drive
PHP на Windows и IIS7
Установка и настройка PHP для использования с модулем FastCGI.
Установка и настройка модуля FastCGI на IIS7.
Если у вас у IIS7, то что-то мне подсказывает о названии вашей операционной
системы — Windows Vista? Не угадал, тогда Windows Server 2008! Либо вы хакер и
поставили IIS7 еще-куда-то, но это нестандартное решение и мы его не
поддерживаем ;).
Шаг 1. Установка FastCGI
Хочу обрадовать сразу — в IIS7, идущем с Windows Server 2008 и Windows Vista
Service Pack 1 модуль FastCGI уже включен. Его необходимо лишь подключить в
настройках. Для этого на Vista нужно открыть Control Panel -> Programs и выбрать
«Turn Windows Features On or Off»:
После этого необходимо установить фичу в IIS: Internet Information Services
-> World Wide Web Services -> Application Development Features -> CGI. При этом
будет установлена поддержка и CGI и FastCGI.
На Windows Server 2008 процесс аналогичен: Server Manager -> Roles -> Add
Role Services -> Web Server -> Application Development -> CGI.
Собственно все, что требуется для включения модуля FastCGI.
Шаг 2. Конфигурация IIS7
1. Открыть IIS Manager, выбрать узел (сервер) для которого нужно настроить
поддержку PHP. И далее выбрать Handler Mappings.
2. Выбираем на странице Handler Mappings ссылку Add Module Mapping и
заполняем окно следующими значениями:
Request path: *.php (обработка всех файлов с расширением .php)
Module: FastCgiModule (модуль FastCGI)
Executable: C:\Web\PHP\php-cgi.exe (путь к PHP)
Name: PHP (имя для удобства)
После добавления этой настройки появится окно с вопросом о регистрации
FastCGI приложения для этого обработчика. Подтверждаем.
Описанные выше действия привели к созданию в директории PhpSites следующего
web.config файла:
xml version =«1.0» encoding =«UTF-8» ? >
configuration >
system.webServer >
handlers >
add name =«PHP» path =»*.php» verb =»*»
modules =«FastCgiModule» scriptProcessor =»C:\Web\PHP\php-cgi.exe»
resourceType =«Unspecified»/>
handlers >
system.webServer >
configuration >
* This source code was highlighted with Source Code Highlighter .
Теперь можно переходить к проверке работоспособности PHP.
Шаг 3. Проверяем корректность настройки
В директории узла для которого мы сконфигурировали PHP создаем файл
index.php:
И обращаемся к этому файлу через HTTP запрос. В результате, если все хорошо и
наша карма не испорчена, запрос будет корректно обработан:
Рекомендации по настройке PHP на
IIS7
Частота перезапуска процессов PHP
Поскольку при использовании PHP на
IIS7 с использованием FastCGI
модуля, сам модуль FastCGI берет на себя
управление процессами и ресурсами, необходимо убедится, что механизм перезапуска
процессов (recycling) в PHP
не будет мешать FastCGI. Это легко сделать, если
настроить FastCGI так, чтобы он всегда перезапускал
процессы раньше, чем это сделает PHP.
В настройках FastCGI существует настройка
instanceMaxRequests, определяющая после обработки какого количества запросов,
процесс будет перезапущен. В PHP аналогичный параметр
задается значением переменной PHP_FCGI_MAX_REQUESTS. Очевидно, чтобы дать
возможность FastCGI рулить процессом, достаточно
установить instanceMaxRequests fastCgi >
application fullPath =»C:\inetpub\php\php-cgi.exe»
maxInstances =«4» instanceMaxRequests =«10000» >
environmentVariables >
environmentVariable name =«PHP_FCGI_MAX_REQUESTS» value =«10000» >
environmentVariables >
application >
fastCgi >
* This source code was highlighted with Source Code Highlighter .
Использование нескольких версий PHP
fastCgi >
application fullPath =«C:\inetpub\php\php-cgi.exe» >
.
application >
application fullPath =«C:\inetpub\php4\php4.exe» >
.
application >
application fullPath =«C:\inetpub\php41\php41.exe» >
.
application >
fastCgi >
* This source code was highlighted with Source Code Highlighter .
handlers >
add name =«PHP4» path =»*.php» verb =»*» modules =«FastCgiModule»
scriptProcessor =»C:\inetpub\php\php41.exe»
resourceType =«Unspecified»/>
handlers >
* This source code was highlighted with Source Code Highlighter .
Общие инструкции по установке
Перед началом установки вы должны знать, для чего вы хотите использовать PHP. Вы можете использовать PHP для целей, описанных в разделе Что может PHP?
- Создавать веб-сайты и веб-приложения (Скрипты на стороне сервера)
- Скрипты командной строки
- GUI-приложения (Приложения с графическим интерфейсом пользователя)
Для первой и наиболее распространённой цели вам нужны три вещи: Сам PHP, веб-сервер и веб-браузер. Вероятно, у вас уже есть веб-браузер и, в зависимости от настроек вашей операционной системы, вы также можете иметь и веб-сервер (например, Apache в Linux и macOS; IIS в Windows). Также вы можете арендовать веб-сервер или некоторое дисковое пространство на веб-сервере. В этом случае вам не нужно устанавливать дополнительное программное обеспечение, только писать PHP-скрипты, загружать их на сервер и просматривать результат их работы в браузере.
В случае установки сервера и PHP самостоятельно у вас есть два варианта установки PHP. Для многих серверов PHP может быть установлен как модуль сервера. Это возможно для таких серверов, как Apache, Microsoft Internet Information Server, Netscape и iPlanet. Если PHP не поддерживает интерфейс для вашего сервера, вы всегда можете использовать его как обработчик CGI или FastCGI. Это означает, что вы должны настроить ваш сервер так, чтобы он исполнял все PHP файлы, как CGI-скрипты.
Если вы также собираетесь использовать PHP в командной строке (для генерации изображений, обработки текстов и т.д.), то вам понадобится PHP CLI. Подробнее об этом можно прочитать в разделе Использование PHP в командной строке. В этом случае вам не понадобятся ни сервер, ни браузер.
Вы также можете создавать приложения с графическим интерфейсом, используя при этом расширение PHP-GTK. Это требует абсолютно другого подхода, чем программирование под Веб, т.к. вы не выводите HTML или текст, а управляете окнами при помощи PHP. Для получения более полной информации о PHP-GTK » посетите сайт, посвящённый этому расширению . PHP-GTK не включён в стандартную поставку PHP.
Начиная с этого момента мы будем описывать установку PHP для веб-серверов на Unix и Windows, как модуля сервера и как CGI. Вы также можете найти информацию об использовании PHP в командной строке в следующих разделах.