Установка

Этот раздел содержит общие вопросы по установке PHP. PHP доступен практически для любой ОС (за исключением, может быть, MacOS предшествующей OSX) и любого web сервера.

Для установки PHP следуйте инструкциям в Установка и настройка.

  1. Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?
  2. Unix/Windows: Где должен находиться файл php.ini?
  3. Unix: Я установил PHP, но каждый раз при загрузке документа я получаю сообщение 'Document Contains No Data' (Документ Не Содержит Данных)! Что происходит?
  4. Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы! Что происходит?
  5. Unix: Я установил заплатку в Apache для расширений FrontPage и неожиданно PHP перестал работать. Неужели PHP не совместим с FrontPage расширениями для Apache?
  6. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю пустой экран.
  7. Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку сервера 500.
  8. Некоторые операционные системы: Я установил PHP без ошибок, но когда я пытаюсь запустить Apache, я получаю ошибки "undefined symbol" (неопределенный символ): [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS работать вместе!
  11. Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami, я получаю следующую ошибку: Security Alert! PHP CGI cannot be accessed directly..
  12. Как узнать, что мой php.ini был найден и прочтен? Похоже, что мои изменения не были восприняты?
  13. Как на Windows добавить мою PHP директорию в PATH?
  14. Как в Windows сделать файл php.ini доступным для PHP?
  15. Возможно ли использовать согласование содержания в Apache (опция MultiViews) c PHP?
  16. PHP может обрабатывать только GET и POST запросы?
Почему я не должен использовать Apache2 с потоковым MPM в промышленном окружении?

PHP - это клей. Клей, используемый для построения классных веб-приложений, склеивая дюжины сторонних библиотек и создавая впечатление одного согласованного целого, с помощью интуитивного и легко изучаемого языка. Гибкость и мощь PHP полагается на стабильность и устойчивость используемой платформы. Для склейки вместе ему необходимы работающая ОС, работающий веб-сервер и работающие сторонние библиотеки. Когда что-либо из этого перестает работать, PHP нужны способы определения проблем и их быстрого исправления. Если вы усложняете низлежащую систему, не разделяя полностью потоки выполнения, не выделяя раздельные сегменты памяти и не предоставляя "песочницу" для игры для каждого запроса, то в вашей PHP системе появятся слабые места.

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

Unix/Windows: Где должен находиться файл php.ini?

На Unix по умолчанию он должен находиться в директории /usr/local/lib, определяемой как <install-path>/lib. Большинство людей изменяют его во время компиляции с помощью опции --with-config-file-path Для примера, вы можете задать что-то типа:

--with-config-file-path=/etc
Затем скопировать файл php.ini-development из дистрибутива в /etc/php.ini и отредактировать его для ваших локальных нужд.

--with-config-file-scan-dir=PATH

На Windows по умолчанию php.ini находится в Windows директории. Если вы используете веб-сервер Apache, php.ini сначала ищется в директории, где был установлен Apache, например, c:\program files\apache group\apache. В этом случае на одной машине у вас могут быть разные файлы php.ini для разных версий Apache.

Смотрите также главу о конфигурационном файле.

Unix: Я установил PHP, но каждый раз при загрузке документа я получаю сообщение 'Document Contains No Data' (Документ Не Содержит Данных)! Что происходит?

Вероятно, PHP падает по какой-то причине. Для того, чтобы убедиться в этом, просмотрите лог ошибок вашего сервера и затем попытайтесь воспроизвести проблему с помощью небольшого тестового примера. Если вы умеете пользоваться 'gdb', то добавьте трассировку к вашему сообщению об ошибке, это поможет разработчикам точно определить проблему. Если вы используете PHP как модуль Apache, попробуйте что-то типа:

  • Остановите ваши httpd процессы

  • gdb httpd

  • Остановите ваши httpd процессы

  • > run -X -f /path/to/httpd.conf

  • Затем вызовите URL, на котором возникает проблема, из вашего браузера

  • > run -X -f /path/to/httpd.conf

  • Если вы получаете дамп, gdb должен сейчас же сообщить вам об этом

  • введите: bt

  • Вам необходимо включить трассировку в ваше сообщение об ошибке, которое должно быть отправлено с » http://bugs.php.net/

Если ваш скрипт использует функции регулярных выражений (preg_match() и другие), то вам необходимо убедиться, что вы скомпилировали PHP и Apache с одним и тем же пакетом регулярных выражений. Это должно происходить автоматически для PHP и Apache 1.3.x

Unix: Я установил PHP с помощью RPMS, но Apache не обрабатывает PHP страницы! Что происходит?

Предполагается, что Apache и PHP оба были установлены из пакетов RPM. Вам требуется в вашем файле httpd.conf раскомментировать или добавить все или некоторые из следующих строк:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
И добавить:
AddType application/x-httpd-php .php
... в глобальные свойства или в свойства VirtualDomain, для которого вы хотите иметь поддержку PHP.

Unix: Я установил заплатку в Apache для расширений FrontPage и неожиданно PHP перестал работать. Неужели PHP не совместим с FrontPage расширениями для Apache?

Нет, PHP прекрасно работает с FrontPage расширениями. Проблема в том, что FrontPage заплатка изменяет некоторые важные для PHP структуры. Перекомпиляция PHP (с помощью 'make clean ; make') после установки FP заплатки должна решить эту проблему.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю пустой экран.

Сделайте просмотр исходника ('view source') в web браузере и, вероятно, вы увидите исходный код вашего PHP скрипта. Это означает, что web сервер не передал скрипт PHP для интерпретации. Что-то не так с конфигурацией сервера, проверьте конфигурацию сервера согласно установочным инструкциям PHP.

Unix/Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку сервера 500.

Что-то произошло, когда сервер пытался выполнить PHP. Чтобы увидеть более вразумительное сообщение об ошибке, используя командную строку, перейдите в директорию где находится исполняемый файл PHP (php.exe на Windows) и запустите php -i. Если при запуске PHP возникли какие-либо проблемы, то появится соответствующее сообщение об ошибке, которое может дать вам понять что делать дальше. Если вы получаете экран, заполненый HTML кодом (вывод функции phpinfo()), то PHP работает и ваша проблема возможно связана с конфигурацией вашего сервера, которую вам необходимо проверить.

Некоторые операционные системы: Я установил PHP без ошибок, но когда я пытаюсь запустить Apache, я получаю ошибки "undefined symbol" (неопределенный символ):
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

На самом деле это связано с клиентскими библиотеками MySQL и не имеет никакого отношения к PHP. Одним нужна опция --with-zlib , другим - нет. Это также описано в MySQL FAQ.

Windows: Я установил PHP, но когда я пытаюсь вызвать PHP скрипт из моего браузера, я получаю ошибку:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

Это сообщение об ошибке означает, что PHP не смог вывести абсолютно ничего. Чтобы увидеть более вразумительное сообщение об ошибке, используя командную строку, перейдите в директорию, где находится исполняемый файл PHP (php.exe на Windows) и запустите php -i. Если при запуске PHP возникли какие-либо проблемы, то появится соответствующее сообщение об ошибке, которое может дать вам понять, что делать дальше. Если вы получаете экран, заполненый HTML кодом (вывод функции phpinfo() функции), то PHP работает.

Как только PHP заработает из командной строки, попытайтесь опять вызвать скрипт из браузера. Если он все также не работает, то причина может быть одной из следующих:

  • Анонимный пользователь Internet ISUR_<machinename> не имеет доступ к вашему PHP скрипту, php.exe, php4ts.dll, php.ini или любому загружаемому PHP расширению из за прав доступа, установленных на эти файлы.
  • Файл скрипта не существует (или, вероятно, не там где вы думаете он должен быть, относительно вашей корневой web директории). Заметьте, что для IIS вы можете поймать эту ошибку пометив 'check file exists' при настройке ассоциирования скриптов (script mappings) в Администраторе Internet Сервисов (Internet Services Manager). Если файл скрипта не существует, то сервер выдаст ошибку 404. Также есть дополнительное преимущество, заключащееся в том, что IIS будет выполнять необходимую вам аутентификацию, основываясь на NTLanMan правах доступа на ваш скрипт.
Windows: Я следовал всем инструкциям, но так и не смог заставить PHP и IIS работать вместе!

Убедитесь что все пользователи, кому необходимо запускать PHP скрипты, имеют право выполнять php.exe! IIS использует анонимного пользователя, который добавлен во время установки IIS. Этот пользователь должен иметь права на php.exe. Также любому аутентифицированному пользователю будут нужны права на выполнение php.exe. И для IIS4 вам необходимо сказать ему, что PHP является скриптовой системой. Также вам захочется прочитать это.

Когда PHP запускается как CGI в IIS, PWS, OmniHTTPD или Xitami, я получаю следующую ошибку: Security Alert! PHP CGI cannot be accessed directly..

Вы должны установить директиву cgi.force_redirect в 0. По умолчанию она установлена в 1, поэтому убедитесь, что директива не закоментирована (с ;). Как все директивы, она задается в php.ini

Так как значение по умолчанию 1, то очень важно быть уверенным на 100%, что был прочитан верный php.ini файл. Для подробностей читайте здесь.

Как узнать, что мой php.ini был найден и прочтен? Похоже, что мои изменения не были восприняты?

Чтобы убедиться, что PHP прочитал ваш php.ini, вызовите phpinfo() и недалеко от начала будет находиться строка, озаглавленная Configuration File (php.ini). Она скажет вам, где PHP ищет php.ini и был ли файл прочитан. Если указана только директория, то файл не был прочитан и вы должны поместить ваш php.ini в эту директорию. Если php.ini включен в PATH, то он был прочитан.

Если php.ini был прочитан и вы запускаете PHP как модуль, то не забудьте перезапустить ваш web сервер после внесения изменений в php.ini.

Смотрите также php_ini_loaded_file().

Как на Windows добавить мою PHP директорию в PATH?

На Windows NT+ и Windows Server 2000+:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings -> Control Panel -> System, или просто Start -> Control Panel -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку 'Environment Variables'

  • Смотрите в окошко 'System Variables'

  • Найдите Path (возможно, вам придется сделать прокрутку, чтобы найти его)

  • Двойной щелчок на Path

  • Добавьте в конец вашу PHP директорию, поставив спереди ';' (например ;C:\php)

  • Нажмите OK

На Windows 98/Me вам необходимо отредактировать файл autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:\autoexec.bat

  • Найдите строку с PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... и добавьте в конец строки: ;C:\php

  • Сохраните файл и перезапустите ваш компьютер

Замечание: Обязательно перезагрузитесь после указанных шагов для уверенности, что внесенные вами изменения были применены к PATH.

Прежде в руководстве по PHP рекомендовалось копировать файлы в системную директорию Windows, так как эта директория (C:\Windows, C:\WINNT и т.п.) входит в системный PATH по умолчанию. Копирование файлов в системную директорию Windows давно уже противопоказано и может вызвать проблемы.

Как в Windows сделать файл php.ini доступным для PHP?

Для этого есть несколько путей. Если вы используете Apache, то читайте инструкции по его установке (Apache 1, Apache 2), в ином случае, вы должны установить переменную окружения PHPRC:

На Windows NT, 2000, XP и 2003:

  • Зайдите в Control Panel и откройте системную иконку (Start -> Settings -> Control Panel -> System, или просто Start -> Control Panel -> System for Windows XP/2003)

  • Перейдите в закладку Advanced

  • Нажмите кнопку 'Environment Variables'

  • Посмотрите в окошко 'System variables'

  • Щелкните на 'New' и введите 'PHPRC' как имя переменной и директорию, где находится php.ini, как значение переменной (например, C:\php)

  • Нажмите OK и перезапустите ваш компьютер

На Windows 98/Me вам необходимо отредактировать файл autoexec.bat:

  • Откройте Notepad (Start -> Run и введите notepad)

  • Откройте файл C:\autoexec.bat

  • Добавьте новую строку в конец файла: set PHPRC=C:\php (замените C:\php на директорию, где находится php.ini). Учтите, что путь не должен содержать пробелы. Например, если вы установили PHP в C:\Program Files\PHP, вы можете вместо этого ввести C:\PROGRA~1\PHP.

  • Сохраните файл и перезапустите ваш компьютер

Возможно ли использовать согласование содержания в Apache (опция MultiViews) c PHP?

Все работает замечательно, если ссылки на PHP файлы имеют расширение. Этот FAQ рассматривает только случай, когда ссылки на PHP файлы не имеют расширения и вы хотите использовать согласование содержания для отбора PHP файлов из URL без расширений. В этом случае, замените строку AddType application/x-httpd-php .php на:

AddHandler php5-script php
AddType text/html php
Это решение не работает в Apache 1, так как в нем PHP модуль не ловит php-script.

PHP может обрабатывать только GET и POST запросы?

Нет, можно обрабатывать любые запросы, например, CONNECT. Необходимый статус ответа можно послать с помощью функции header(). Если нужно обрабатывать только GET и POST запросы, то этого можно достигнуть с помощью такой конфигурации Apache:

<LimitExcept GET POST>
Deny from all
</LimitExcept>

Коментарии

INSTALLATION ON OPENBSD 3.1 VIA PORTS COLLECTION
Would have succeed but no mysql support. 
I commented out the FLAVORS+= dbase filepro mysql mysql_bundled postgresql iodbc in the /usr/ports/www/php4/Makefile and in the configure options added 
--with-mysql=/usr/local   and it worked. 

Good Luck
2002-05-18 01:32:20
http://php5.kiev.ua/manual/ru/faq.installation.html
Running Win2K AS + IIS5.0 + PHP 4.3.1, I ran into a nasty problem that I mistakenly thought had to do with something in the php.ini configuration. When I would try to submit a form using the HTTP method GET it would work, but I would get a "404 Page Not Found" error using the POST method. 

All my permissions were set correctly, the php.ini was configured correctly. It had to do with URLScan being installed on IIS (see below)

Page 404 File Not Found Error When Using POST method in PHP (and Perl, and otherwise)
-------------------------------------------

This is related to the Microsoft URLScan utility. If you have this problem, the IIS administrator has probably run the IIS Lockdown tool as well as configured URLScan to reject this type of HTTP method when sent in a URL. These tools are meant to enhance web server security.

URLScan configuration files can be found in the \WINNT\system32\inetsrv\urlscan folder on the web server. Specifically, the file to modify is urlscan.ini.

The changes to make are as follows:
1. Make sure UseAllowVerbs=1 under [options]
2. Under the [AllowVerbs] section, list your allowed HTTP methods to include:
    GET
    POST

For more information on the IIS Lockdown tool and URLScan, visit http://technet.microsoft.com
2003-03-06 14:36:10
http://php5.kiev.ua/manual/ru/faq.installation.html
PHP 4 and IIS 6.0 (Windows Server 2003)

Had difficulty getting PHP 4.3.3 to work with Win2003 Ent Server for use with SquirrelMail.  Problem found and believed solved.  Appears to be something New with IIS 6.0 (More security by Micro$oft)  Was getting 404 error and php was not being run as a cgi even though it was in extensions and IIS user had rights to execute it. (php from command line operated correctly)

If you are installing on Windows Server 2003 (only have Enterprise Edition ? Not sure if this applies to standard edition), and you have done the normal procedures for inclusion of PHP scripts (either ISAPI or CGI) in IIS, you will still get a 404 error when attempting to execute those scripts even though IIS has rights and the extension points to the correct file.  To alleviate this problem, perform the following:

1.    Open a command prompt window
2.    Change to C:\windows\system32
3.    Execute the command:  cscript  iisext.vbs /AddFile c:\php\php.exe 1 php 0 php
4.    Execute the command:  cscript iisext.vbs /EnFile c:\php\php.exe
5.    To check for correct execution of the above,
6.    Execute the command:  cscript IisExt.vbs /ListFile ? the php extension should be listed

If you try just step 4 without step 3 you get an error that the file is not in the list (and won?t be there till you do step 3 above)

After this, IIS seems to like the php extension and work normally.

For additional reference, see the below 3 Micro$oft KB Articles:
HOWTO: Enable and Disable ISAPI Extensions and CGI Applications in IIS 6.0 (MS KB Article 328360)

HOWTO List Web Server Extensions and Extension Files in IIS 6.0 (MS KB Article 328505)

HOWTO Add and Remove Web Service Extension Files in IIS 6.0 (MS KB Article 328419)
2003-11-29 21:33:58
http://php5.kiev.ua/manual/ru/faq.installation.html
Finally got IIS 5 and PHP 5 to talk. 

What worked for me was:

1) Set
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
W3SVC\Parameters\Script Map]
".php"="your path to php\\php.exe"

2) ensure there is not a php.ini in the windows system folder and that there is one wherever you've put PHP

3) edit php.ini and set cgi force redirect to 0 and cgi.rfc2616_headers = 1

4) Put the PHP scripts in their own folder underneath the inetpub root

5) Open the IIS console, right click your new php folder
In the Directory tab
 set application name to the name of the folder
 set executable and script as permission
 set application protection to low
Click configuration and check that .php is mapped to wherever you put
PHP

Restart IIS

Try a very simple PHP page and it should work

Nigel
2003-12-13 19:00:23
http://php5.kiev.ua/manual/ru/faq.installation.html
As stated within the note "jimo at mail dot azhsv dot com
29-Nov-2003 04:33 
PHP 4 and IIS 6.0 (Windows Server 2003)," I found the same steps were requiered for installation of PhP 5 beta 3 on my Windows 2003 server (Standard Edition)
2004-02-01 15:51:00
http://php5.kiev.ua/manual/ru/faq.installation.html
Fixing 404 (file not found) errors with PHP 5.0.3 and IIS 6.0

IIS 6.0 is installed with security settings that don't permit dynamic content.  This means that even if all the hints in the FAQ are paid attention to (.ini modified correctly, security and permissions correct for IUSR_xxx user, etc), you still get 404 errors for all php files. 

To fix this:  IIS Manager -> expand local computer -> Web Services Extensions -> Add web service or extension -> .php, browse to c:\php\php-cgi.exe or wherever you had the php executable installed. That plus setting the doc_root in the .ini file solved the problem.

--BF
2005-01-04 11:22:13
http://php5.kiev.ua/manual/ru/faq.installation.html
Installing PHP 4 or 5 on Windows Server 2003 x64 results in http error 505. This is not a PHP bug. It is due to running a 32-bit ISAPI DLL under the 64-bit version of IIS 6, as documented here: http://support.microsoft.com/?id=895976

Solution: Flip the Metabase flag for Enable32bitAppOnWin64 as described in http://support.microsoft.com/?id=894435 , 
like this: CSCRIPT ADSUTIL.VBS SET W3SVC/AppPools/Enable32bitAppOnWin64 1

(Alternatively with full path: cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1)
2005-07-12 04:22:40
http://php5.kiev.ua/manual/ru/faq.installation.html
Автор:
<LimitExcept GET POST>
Deny from all
</LimitExcept>

Does not work with Apache2+ & PHP5 . Apache Refuses to start
2005-08-14 14:23:07
http://php5.kiev.ua/manual/ru/faq.installation.html
You do not have to restart the whole system make effect of changing the PATH env var. For me (sbs2003) worked automatically.
on older systems you can use

set $Path=%path%;c:\php

command to extend immediately the path var.
2006-01-01 02:36:47
http://php5.kiev.ua/manual/ru/faq.installation.html
Автор:
After setting the PHPRC environment variable, none of my PHP files would hit the preprocessor. The browser was just serving out PHP source code right there in the "view source."

The manual was telling me to set this var to "c:\php," but nothing was working. It's almost as if IIS/Win2000 wasn't reading my php.ini at all.

After I set that variable to "c:\php\php.ini," all of a sudden I was getting honest to goodness PHP pages working.
2006-09-13 22:03:03
http://php5.kiev.ua/manual/ru/faq.installation.html
I recntly upgraded from PHP 5.1 to 5.2 on my Windows Server 2003 using IIS6. I selected CGI as before. My PHP folder is as always C:\Program Files\PHP. I also edited my brand new php.ini, enabling all my old extensions and recommended settings for IIS. I like not to keep my old config into a new version.

After upgrade, I just got blank pages in my browser, and the response status was 404 Not found.

I checked my installation twice, using this FAQ, but got no way.

Then I went to IIS Manager, Web Service Extensions. The php Service Extension was Allowed as it should. I deleted the Service Extension and added it. The old extension used short file names containing tilde (PROGRA~) character, but I don'æt know if that gas anything to do with the problem. Anyway, after allowing my" new" Service Extension, pointing to php-cgi.exe as before, mye web sites suddenly worked. So will revommend anyone with thos problem to delete and add the Servcie Extension. It didn't help re-allowing it, restarting IIS or the complete server.
2006-11-06 23:15:20
http://php5.kiev.ua/manual/ru/faq.installation.html
Автор:
I have some additional troubleshooting tips for 53.7, which deals with getting a blank screen on your browser when running a PHP script.

In addition to server misconfiguration, it may also be that PHP isn't configured to output errors to the browser, which is the case if you or your host uses a more secure php.ini. If this is the case, you need to find out where errors are being logged to find out if any errors are preventing normal output from being delivered to the client.

If you have access to php.ini, check the 'display_errors' directive, which is, by default, located under the 'error_reporting' directive. It's helpful to have 'display_errors' on during debugging phases, but best to have it off in production environments.

Related functions: http://php.net/ini_set | http://php.net/error_reporting | http://php.net/error_log
2007-05-18 22:39:44
http://php5.kiev.ua/manual/ru/faq.installation.html
Had a hard day to MSI install 5.2.3 on WinXP with MySQL. I use a drive substitution (subst drive: path - in my case subst d: c:\drive_d) and installed PHP in D:\PHP - which in reality is C:\DRIVE_D\PHP.  To make a long story short - only after (1) changing all substituted D:\ back to C:\DRIVE_D and (2) resolving all DOS short names to Win long names PHP started to work. The first one is clear - the substitution works only for the active console user - not for services or IUSR. For the second one I have no explanation, since DOS short names should work systemwide - maybe Win handles them correctly but PHP not ?

BTW <?php phpinfo(); ?> was of tremendeous help

Meiki
2007-06-07 19:41:32
http://php5.kiev.ua/manual/ru/faq.installation.html
For Windows XP users

Just add php.ini to windows/system 32 and also save a copy in the setup folder e.g. c:/php/php.ini, c:/php5/php.ini, 

You have to follow the suggestions, add to path, uncomment extensions and voila!!
2007-07-16 18:39:27
http://php5.kiev.ua/manual/ru/faq.installation.html
Windows 2000 Server and IIS (SP4 and all patches):

After many frustrating hours of trying to figure out the install (again), It took a while, but here are a couple tips:

PHP working with IIS uses c:\winnt\php.ini

It doesn't matter what you set the path to, nor what you set the PHPRC environment variable to. After you get PHP running correctly in the installation folder (using php -i) copy the php.ini file into the c:\winnt folder.

Here's what worked for me:

- Add PHP path to System environment variable

- Add php5activescript.dll from http://snaps.php.net/ to the PHP folder, then Register it: "regsvr32 php5activescript.dll"

Set extension_dir and doc_root directives in PHP.INI:
  extension_dir = C:\WWW\PHP\ext
  doc_root = C:\WWW\Site
  cgi.force_redirect = 0

(the last cgi.force_redirect isn't required, but I like to set it anyway)

Copy the .INI file into WINNT folder

In IIS Manager, right-click "Default Web Site", Click "Home Directory",
  Click "Configuration", "Add" the ISAPI application:
    Executable: <your php install>\php5isapi.dll
    Extension: .php
    Limit to: GET,HEAD,POST
    Check: "Script Engine"
    Uncheck: "Check that file exists"

Finally: Set up an ISAPI filter:
  Click the "ISAPI Filters" tab,
  Filter Name: PHP
  Executable: <your php install>\php5isapi.dll

Notes: You don't have to set any of your folders as "Script source" folders. .PHP files aren't scripts, merely text files that require processing before being shipped off to the browser, which is what the ISAPI filter does.

Finally, working again.

Chase
2007-09-20 00:18:38
http://php5.kiev.ua/manual/ru/faq.installation.html
To limit HTTP Request Methods on the Apache server running PHP you should use mod_rewrite or mod_security instead of LimitExcept, to give you more control over the handling of such http errors.  Can go in .htaccess file or httpd.conf

# mod_rewrite
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD|POST)$
  RewriteRule .* - [F,L]
</IfModule>

# mod_security
<IfModule mod_security.c>
  SecFilterSelective REQUEST_METHOD "!^(GET|HEAD|POST)$" "deny,log,status:403"
</IfModule>

You can use the php request method scanner at askapache to see exactly how your server deals with various request methods, and check that your server is configured properly.. 

http://www.askapache.com/online-tools/request-method-scanner/
2007-11-02 16:35:39
http://php5.kiev.ua/manual/ru/faq.installation.html
One final note to the message below if you are getting the message about not having rights to execute...You need to use IIS right click on the website and choose 'Properties/Home Directory' then on the 'Execute Permissions' combo box you need to choose 'Scripts only'...Click ok...another dialog may appear asking which directories to apply the action too...choose any directories that you intend on using php in and click ok...It should work now...
2008-04-17 22:30:29
http://php5.kiev.ua/manual/ru/faq.installation.html
WINDOWS 2003 and IIS.  BIG LESSON FOR ME was "don't mess with the optional components". 
I had lots of trouble until I tried installing without asking for extras and then it was very smooth.
I have found no need to set up paths. 
I have found no need to configure IIS. 
I have found no need to change security on the PHP folder.

What works for me with Windows/IIS:

1.  You need to be logged-on as "administrator"

2.  Run  "php-5.2.6-win32-installer.msi"
Your ONLY action during this wizard is to select "IIS ISAPI" as the webserver.  Do NOT CHANGE anything else!  I am guessing that the optional extras apply only to Apache because after enabling them I see Apache-related error messages.

3.  Setup a test virtual directory as you would for an ASP or ASP.NET web app.  eg "phptest"
Then use notepad to create a test page eg "test.php"
<?php
phpinfo
();
?> 

4.  In Internet Explorer, test with eg this address
http://localhost/phptest/test.php

IF this does not give you a beautiful page of details THEN start reading other advice on this page - especially helpful for me was the faq advice to test run "php.exe -i" from the command prompt.
2008-05-04 01:19:14
http://php5.kiev.ua/manual/ru/faq.installation.html
Here are my struggle to get PHP 5.2.12 working on Windows XP SP3, IIS 5.1 (Please note Win XP SP3 has issue of FastCGI)

1. Dowloaded installer and installed in C:\Program Files\PHP as ISAPI module

---->Did not work

Added php5isapi.dll in ISAPI Filter and added the extension .php in Home Dir->Configuration
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

(And the Google was pointing to the Fast CGI issue; Don't know why microsoft has MS-FAST ! )
Uninstalled the PHP and cleaned up the folders, PATH environment variable & PHPRC, the IIS settings and registry entries and shut down(restart is different from shut down) the system to make it very clean

2. Reinstalled the PHP in C:\PHP as ISAPI and did the same as above in IIS
(For every setting change restarted IIS on cmd->iisreset)

---->Did not work

Uninstalled and cleaned up same as above and took a breath to make sure what I am doing wrong.
Shutdown the system.

3. Unzipped the php-5.2.12-Win32.zip and did the same as above (this time manually PATH variable and security permission for the PHP folder and following settings)

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0 

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system.

4. Downloaded Microsoft Web Platform Installer 2.0 and select the PHP+Fast CGI+Windows Cache for PHP extension and Web Deployment Tools
restarted the system to take effect the settings

---->Did not work

Uninstalled and cleaned up same as above
Shutdown the system

5. Took the prev version of PHP php-5.2.4-Win32.zip unzip the folder and did the following changes:

short_open_tag = On
error_reporting = E_ALL & ~E_NOTICE
display_errors = On
doc_root = "C:\Inetpub\wwwroot"
extension_dir = "C:\PHP\ext"
cgi.force_redirect = 0

set the security permission as IIS_machinename with full access to the C:\PHP folder

------->IT GOT WOKRING

Hope people would be aware of php-5.2.12 and would love the php-5.2.4
2010-03-12 04:28:09
http://php5.kiev.ua/manual/ru/faq.installation.html

    Поддержать сайт на родительском проекте КГБ