Как php подключить к apache на windows

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

Этот раздел содержит примечания и подсказки к установке 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

8 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...

Начнём с того, что скачаем самую новую версию PHP для Windows с официального сайта: https://windows.php.net/download/

Там несколько вариантов, которые различаются:

  • версией (например, 7.2, 7.1, 7.0, 5.6)
  • битностью (64 и 32)
  • Thread Safe или Non Thread Safe

Выбирайте самую последнюю версию, с той битностью, какая у вашего сервера. Т.е. если у вас Apache 64-битный, то PHP также должен быть 64-битным. Всегда выбирайте Thread Safe версию.

Для каждого файла имеется две ссылки:

  • Zip
  • Debug Pack

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

Настройка выполняется в два этапа:

  • подключение PHP к Apache
  • изменение настроек самого PHP (какие расширения включены, сколько выделено памяти PHP скриптам и т.д.)

Подключение PHP к Apache

Для подключения PHP к Apache откройте конфигурационный файл веб-сервера, который расположен по следующему пути: Apache24confhttpd.conf (в папке сервера, в подпапке conf, файл httpd.conf).

В этот файл добавьте три строки, две из которых нужно откорректировать:

PHPIniDir "C:/путь/до/PHP"
AddHandler application/x-httpd-php .php
LoadModule php_module "C:/путь/до/PHP/php8apache2_4.dll"

В первой строке вместо C:/путь/до/PHP напишите точный путь до папки, куда вы распаковали файлы PHP. В третьей строке C:/путь/до/PHP/php8apache2_4.dll также откорректируйте путь, указав расположение PHP папки.

К примеру, я распаковал PHP в папку C:/Server/bin/PHP, тогда мои настройки следующие:

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

Если папка PHP находится в корне диска C, тогда эти строки должны быть такими:

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

Чтобы изменения вступили в силу, перезапустите веб-сервер или компьютер.

Настройка PHP

В папке PHP найдите файл php.ini-development и переименуйте его в php.ini – это нужно сделать обязательно, иначе PHP не будет видеть сделанные настройки.

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

; extension_dir = "ext"

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

extension_dir = "C:путьдоPHPext"

Обратите внимание, что вам нужно скорректировать строку C:путьдоPHPext, указав конкретный путь до папки, где размещены файлы PHP.

У PHP (как и у Apache) имеется много расширений. Если вы не знаете, какое расширение для чего нужно, то как минимум два варианта:

  • начать изучить предназначение каждого расширения и подключить только те, которые вам действительно нужны;
  • подключить самые важные расширения, чтобы любые сайты и движки работали без ошибок.

Чтобы подключить большую часть расширений, найдите группу строк:

;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

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

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

  • Установка Apache, PHP, MySQL и phpMyAdmin на Windows XP (100%)
  • Для чего нужен веб-сервер Apache (100%)
  • Готовая сборка Apache для Windows XP (100%)
  • Ошибки при настройке и установке Apache, PHP, MySQL/MariaDB, phpMyAdmin (100%)
  • Как установить веб-сервер Apache с PHP, MySQL и phpMyAdmin на Windows (100%)
  • Как запустить Apache на Windows (RANDOM — 65.5%)

Последнее обновление: 26.02.2021

Для работы с PHP нам потребуется веб-сервер. Обычно в связке с PHP применяется веб-сервер Apache. Официальный
сайт проекта — https://httpd.apache.org/. Там же можно найти всю подробную информацию о релизах, скачать исходный код.
Однако официальный сайт не предоставляет готовых сборок для ОС Windows.

Перед установкой Apache следует отметить, что если наша ОС Windows, то в системе должны быть установлен пакет для C++, который можно найти по адресу
для 64-битной и для 32-битной.

Итак, если нашей ОС является Windows, перейдем на сайт http://www.apachelounge.com/, который предоставляет дистрибутивы Apache для Windows:

Загрузка веб-сервера Apache

В подпункте Apache 2.4 binaries VS16 выберем последнюю версию дистрибутива сервера. На странице загрузок мы можем
найти две версии пакета Apache — для 64-битных систем и для 32-битных.

После загрузки пакета с Apache распакуем загруженный архив. В нем найдем папку непосредственно с файлами веб-сервера — каталог Apache24.
Переместим данный каталог на диск C, чтобы полный путь к каталогу составлял C:/Apache24.

Запуск Apache

В распакованном архиве в папке bin найдем файл httpd.exe

Запуск веб-сервера Apache

Это исполняемый файл сервера. Запустим его. Нам должна открыться следующая консоль:

веб-сервер Apache httpd.exe

Пока работает это приложение, мы можем обращаться к серверу. Для его тестирования введем в веб-браузере адрес
http:localhost. После этого веб-браузер должен отобразить следующую страницу:

it works в веб-сервере Apache

Эта страница символизирует, что наш веб-сервер работает, и мы можем с ним работать.

Конфигурация веб-сервера

Теперь проведем конфигурацию сервера, чтобы связать его с ранее установленным интерпретатором PHP.. Для этого найдем в папке веб-сервера
в каталоге conf (то есть C:Apache24conf ) файл httpd.conf

конфигурация веб-сервера Apache и связь с PHP

Откроем этот файл в текстовом редакторе. httpd.conf настраивает поведение веб-сервера.
Мы не будем подобно затрагивать его описания, а только лишь произведем небольшие изменения, которые потребуются нам для работы с PHP.

Прежде всего подключим PHP. Для этого нам надо подключить модуль php, предназначенный для работы с apache. В частности, в папке
php мы можем найти файл php8apache2_4.dll:

php8apache2_4.dll и веб-сервер Apache и связь с PHP

Для подключения php найдем в файле httpd.conf конец блока загрузки модулей LoadModule

//......................
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
#LoadModule watchdog_module modules/mod_watchdog.so
#LoadModule xml2enc_module modules/mod_xml2enc.so

И в конце этого блока добавим строчки

LoadModule php_module "C:/php/php8apache2_4.dll"
PHPIniDir "C:/php"

Далее укажем место, где у нас будут храниться сайты. Для этого создадим, например, на диске С каталог localhost. Затем найдем в файле httpd.conf
строку

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

По умолчанию в качестве хранилища документов используется каталог «c:/Apache24/htdocs». Заменим эту строку на следующую:

DocumentRoot "c:/localhost"
<Directory "c:/localhost">

Изменим пути файлам, в которые будут заноситься сведения об ошибках или посещении сайта. Для этого найдем строку

ErrorLog "logs/error.log"

И заменим ее на

ErrorLog "c:/localhost/error.log"

Далее найдем строку

CustomLog "logs/access.log" common

И заменим ее на

CustomLog "c:/localhost/access.log" common

Таким образом, файл error.log, в который записываются ошибки, и файл access.log, в который заносятся все
данные о посещении веб-сайта, будут располагаться в папке c:/localhost.

Затем найдем строчку:

#ServerName www.example.com:80

И заменим ее на

ServerName localhost

Далее найдем блок <IfModule mime_module>:

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig conf/mime.types

И под строкой <IfModule mime_module> добавим две строчки:

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

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

<IfModule mime_module>
	AddType application/x-httpd-php .php
	AddType application/x-httpd-php-source .phps
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig conf/mime.types

В данном случае мы добавили поддержку для файлов с расширением .php и .phps.

И в конце найдем блок <IfModule dir_module>:

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

И заменим его на следующий:

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

В данном случае мы определяем файлы, которые будут выполняться при обращении к корню файла или каталога. То есть по сути определяем главные страницы
веб-сайта: index.html и index.php.

Это минимально необходимая конфигурация, которая нужна для работы с PHP.

Теперь наша задача — убедиться, что php подключен и работает правильно. Для этого перейдем в папку c:/localhost, которую мы создали для хранения
файлов веб-сервера, и добавим в нее обычный текстовый файл. Переименуем его в index.php и внесем в него следующее содержание:

<?php
phpinfo();
?>

В данном случае мы создали простейший скрипт, который выводит общую информацию о PHP.

Теперь заново запустим файл httpd.exe и обратимся к этому скрипту, набрав в строке браузера
адрес http://localhost/index.php

phpinfo

Что тут произошло? При обращении к сайту на локальной машине в качестве адреса указывается http://localhost.
Затем указывается имя ресурса, к которому идет обращение. В данном случае в качестве ресурса используется файл
index.php. И так как в файле httpd.conf в качестве хранилища документов веб-сервера указан каталог C:localhost, то именно в этом каталоге и будет
веб-сервер будет производить поиск нужных файлов.

И поскольку выше при конфигурировании мы указали, что в качестве главной страницы может использоваться файл index.php, то мы можем также обратиться к
этому ресурсу просто http://localhost/

Таким образом, теперь мы можем создавать свои сайты на php.

Установка веб-сервера в качестве службы

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

C:Apache24binhttpd.exe -k install

Установка Apache и PHP

То есть в данном случае прописываем полный путь к файлу httpd.exe (C:Apache24binhttpd.exe) и далее указываем команду на установку службы -k install.

Если установка завершится удачно, то в командная строка отобразит сообщение «The Apache2.4 service is successfully installed». Также будет проведено тестирование сервера.

После установки службы убедимся, что она запущена

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

By
Atul Rai |
Last Updated: April 2, 2022
Previous       Next


In this tutorial, you will learn how to install and configure Apache 2.4 and PHP 8 on a Windows machine. We all know Apache HTTP Server is an open-source cross-platform and free webserver to run web applications and similarly PHP is a free and open-source scripting language used to develop web applications.

To run the PHP code on a Windows machine, first, you’ll need to install and configure a web server (Apache) that executes the PHP application. And on this page, you will find the step-by-step guide on “How to install Apache 2.4 and PHP 8 on a Windows Machine”.

P.S. Tested with Apache 2.4 and PHP 8.1.4 on a Windows 10 machine.

1. Prerequisites

Download the Apache 2.4.x and PHP 8 from its official websites, extract the downloaded file and move it to the C drive.

1.1 Download Apache 2.4.x – Depending on your system build download the binary zip file accordingly.

Download Apache 2.4 - Websparrow.org

1.2 Download PHP 8 – Similarly, depending on your system build download the Thread Safe version of PHP.

Download PHP 8 - Websparrow.org

Before jumping to the main configuration part, be sure you installed latest 14.31.31103.0 Visual C++ Redistributable Visual Studio 2015-2022 : vc_redist_x64 or vc_redist_x86 software.

2. Install Apache

To install the Apache HTTP Server on a local Windows machine move the downloaded and extracted Apache 2.4 binary files to the C drive and follow the below steps:

Step 2.1: Go to the Apache 2.4 bin directory path C:Apache24bin (it might be different in your case) and set it into your system environment variable path.

Set Apache 2.4 in system environment variable- Websparrow.org

Step 2.2: Open the command prompt with admin privileges and run the httpd -k install command to install the Apache services.

C:WINDOWSsystem32>httpd -k install
Installing the 'Apache2.4' service
The 'Apache2.4' service is successfully installed.
Testing httpd.conf....
Errors reported here must be corrected before the service can be started.
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using fe80::ccb2:109d:6198:a489. Set the 'ServerName' directive globally to suppress this message

Step 2.3: Start the Apache service with the command httpd -k start or directly through the Task Manager » Services » Search for Apache2.4 » Right-click on the service » Start.

Start the Apache 2.4 service - Websparrow.org

By default, Apache HTTP Server runs on port 80, make sure no other services/servers running on this port.

Step 2.4: Open the web browser and hit the default Apache localhost URL i.e localhost or localhost:80. If everything is configured correctly, you will see the default index.html web page contents and it is located inside the C:Apache24htdocs directory.

Apache 2.4 configuration successful - Websparrow.org

3. Install PHP 8

The next step is to install PHP 8. To do that, similarly, move the downloaded and extracted PHP 8 binary files to the C drive and follow the below steps:

Step 3.1: Copy the PHP 8 home path i.e C:php-8.1.4 and set it into your machine environment variable.

Set PHP 8 path in system environment variable- Websparrow.org

Step 3.2: Open the command prompt and type php -v to check whether the path is set correctly or not. If the PHP path is set correctly, it will print the PHP version.

C:WINDOWSsystem32>php -v
PHP 8.1.4 (cli) (built: Mar 16 2022 09:33:31) (ZTS Visual C++ 2019 x64)
Copyright (c) The PHP Group
Zend Engine v4.1.4, Copyright (c) Zend Technologies

4. Configure Apache and PHP

Now it’s time to configure Apache HTTP Server with PHP 8.

Step 4.1: Go to the C:Apache24conf directory, inside the conf directory edit the httpd.conf file. Go to the end of the file and add the below configuration because, in Apache, PHP is loaded as a module.

httpd.conf

# Note: Repalce php_module location with your PHP path and
#       if the php8apache2_4.dll is not available, 
#		download the non thread safe version of PHP.

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

Step 4.2: Go to the PHP home directory C:php-8.1.4, and you will find two configuration files php.ini-development and php.ini-production. Create a copy of php.ini-development and rename it to php.ini

PHP configuration file php.ini - Websparrow.org

Step 4.3: Again open the httpd.conf file and search for ServerName, uncomment and edit the ServerName with localhost.

httpd.conf

# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
ServerName localhost

And in the same file also search for DirectoryIndex, and append the default index.php file.

httpd.conf

# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>

Step 4.4: Open the command prompt and run the httpd -t  command to validate whether everything is configured correctly, it will return Syntax OK if everything is configured correctly.

C:WINDOWSsystem32>httpd -t
Syntax OK

5. Test the configuration

To test the Apache 2.4 and PHP 8 configuration, restart the Apache2.4 service from the Task Manager and rename the index.html file to index.php from the C:Apache24htdocs directory and add the below piece of code.

<?php  
 
	echo '<h1>Apache 2.4 and PHP 8 configured successfully-<a href="https://websparrow.org">Websaparrow.org</a></h1>';
	echo ' Your current PHP version is: ' . phpversion(); 
	header("Refresh:10; url=https://websparrow.org");
 
 ?>

Open the web browser and hit the localhost in the URL bar, you will get the following details:

How to install Apache 2.4 and PHP 8 on a Windows Machine

References

  1. Apache HTTP Server Version 2.4 Documentation
  2. PHP Installation on Windows

В этой статье приводится пошаговое руководство по установке PHP для совместной работы с HTTP-сервером Apache на Windows. Эта процедура была протестирована как на Windows XP и Vista. Предполагается, что вы уже завершили установку Apache.

  • Этапы настройки PHP 5
    • 1. Загрузите PHP 5
    • 2. Установите PHP 5
    • 3. Тем, кто обновляет пакет: Удалите старый файл PHP.INI из каталога Windows
    • 4. Настройка PHP
    • Как настроить Apache для PHP 5
    • Запуск PHP 5 в качестве бинарного файла CGI
    • Перезапустите веб-сервер Apache
    • Тестирование установки PHP
    • Изучение PHP

Прежде чем приступать к работе, скачайте копию PHP 5 со страницы загрузки. Загрузите защищенный пакет VC6 из раздела «Windows Binaries» — то есть не скачивайте установщик. Например, выберите пакет с пометкой «PHP 5.2.5 zip package», если на данный момент текущая версия — 5.2.5.

Примечание: обратите внимание, что я не тестировал описанную ниже процедуру с версиями PHP 5.3, только с 5.2.5, которая была последней версией на момент написания статьи. Теоретически, те же действия должны выполняться и для установки PHP 7.

Создайте на жестком диске папку для PHP. Я предлагаю c:php, хотя вы можете использовать другое название и расположение папки. Лично я предпочитаю не использовать имена с пробелами.

Извлеките все файлы из загруженного архива в эту папку. Для этого просто дважды кликните по zip-файлу. А затем перетащите все файлы в папку c:php.

Если вы переходите на PHP 5 с более старой версии, перейдите в каталог Windows, (обычно это c:windows), и удалите все файлы php.ini, которые вы ранее там размещали.

Перейдите в папку c:php и создайте копию файла php.ini-recommended. Назовите новый файл php.ini. Теперь у вас должен быть файл c:phpphp.in с содержимым, идентичным файлу c:phpphp.ini-recommended.

Примечание. Если вы используете Apache 1 нужно либо перенести файл php.ini в каталог Windows (c:windows), либо настроить переменную среды PATH, чтобы включить в нее c:php. Если вы не знаете, как это сделать, просто переместите файл php.ini в папку c:windows. Не нужно этого делать, если используете Apache 2, так как позже мы укажем в файле конфигурации Apache 2 директиву с расположением файла php.ini.

Для установки PHP на Windows 7 c помощью текстового редактора (например, такого как «Блокнот», который можно найти в разделе «Служебные» меню «Пуск»)? откройте файл php.ini. Возможно, придется внести следующие изменения в файл:

а) Включение коротких открывающих тегов

Найдите следующую строку:

Если для short_open_tag задано значение off, теги типа «<?» не будут считаться открывающими тегами для PHP-кода. В таком случае, чтобы начать PHP-скрипт, нужно будет скомпоновать скрипт с открывающим тегом типа «<?php».

Поскольку многие сторонние PHP-скрипты используют формат «<?», установка для этого параметра значения off создаст больше проблем, чем принесет пользы. Особенно, если учесть тот факт, что большинство, коммерческих хостингов, поддерживающих PHP, без проблем обрабатывают скрипты, использующие «< ?», в качестве открывающего тега. Чтобы изменить эту установку, отредактируйте данную строку следующим образом:

b) Волшебные кавычки

При установке Apache PHP по умолчанию входящие данные автоматически не экранируются с помощью слэша. Если вы хотите, чтобы входные данные имели префикс обратной косой черты («»), например, чтобы воспроизводить настройки хостинга, найдите следующую строку:

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

Не рекомендуется делать это, если на хостинге не задан данный параметр. Даже при установленном значении Off вы все равно можете использовать в PHP функцию addslashes(), чтобы добавлять слэши для конкретных частей данных,.

c) Использование глобальных переменных

Ряд старых скриптов при выполнении исходят из того, что все данные, отправляемые через форму, будут автоматически иметь переменную PHP с тем же именем. Например, если в форме есть поле для ввода с именем «something«, старые скрипты PHP исходят из того, что PHP-процессор автоматически создаст переменную с именем $something, которая содержит значение, заданное через это поле.

Если вы используете такие скрипты, нужно найти следующую строку:

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

Предупреждение: при установке PHP на Windows не делайте этого, если у вас нет сторонних скриптов, для работы которых это необходимо. При написании новых скриптов лучше всегда исходить из того, что для элемента register_globals установлено значение «Off«.

d) Отображение ошибок

На «живом» сайте ошибки в скрипте обычно регистрируются без отображения в файле ошибок PHP. Но на локальной машине, пока вы тестируете и отлаживаете PHP-скрипт более удобно отправлять сообщения об ошибках при их выявлении прямо в окно браузера. Так вы не пропустите ошибки, даже если забудете проверить файл журнала ошибок.

Чтобы PHP отображал сообщения об ошибках прямо в окне браузера, найдите следующую строку:

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

Для этого параметра на работающем сайте всегда должно быть установлено значение Off.

e) Путь сессии

Если скрипт использует сессии, найдите следующую строку:

;session.save_path = "/tmp"

session.save_path задает папку, в которой PHP сохраняет файлы сессии. Поскольку папка /tmp в Windows не существует, то нужно установить другую папку. Один из способов — создать папку с именем c:tmp (как ранее мы создали c:php) и указать для этого параметра данную папку. Если сделаете это, измените данную строку следующим образом:

session.save_path = "c:tmp"

Обратите внимание, что в дополнение к изменению пути я также удалил из строки префикс точки с запятой («;»).

Также можно использовать текущую папку TEMP на своем компьютере. Или создайте папку tmp в каталоге PHP, например c:phptmp и соответствующим образом настройте файл конфигурации. Возможных вариантов может быть много. Если вы не можете решить, какой из них выбрать, просто создайте c:php и сделайте, как я сказал выше.

f) Сервер SMTP

При установке PHP 5 5 если скрипт использует функцию mail(), и нужно, чтобы функция успешно отправляла почту на локальном компьютере, найдите следующий раздел:

[mail function]
; For Win32 only.
SMTP = localhost
smtp_port = 25

; For Win32 only.
;sendmail_from = me@example.com

Измените его, указав адрес вашего SMTP-сервера и учетную запись электронной почты. Например, если ваш SMTP-сервер mail.example.com, а адрес электронной почты youremail@example.com, измените код так:

[mail function]
SMTP = mail.example.com
smtp_port = 25
sendmail_from = youremail@example.com

Обратите внимание, что после этого, когда скрипт попытается использовать функцию mail(), для ее успешной работы нужно будет подключиться к своему интернет-провайдеру. Если вы не измените приведенные выше строки и попытаетесь использовать в скрипте функцию mail(), функция вернет код сбоя и отобразит сообщение об ошибке.

Существует два способа установки Apache PHP. Первый: настроить его на загрузку PHP-интерпретатора в качестве модуля Apache. Второй: настроить его для запуска интерпретатора как бинарного CGI. Нужно применять только один из них. Выберите метод модуля, если на хостинге PHP также установлен, как модуль Apache, или используйте метод CGI, если он реализован на хостинге.

a) Запуск PHP 5 в качестве модуля Apache

Чтобы настроить Apache для загрузки PHP в качестве модуля для анализа PHP-скриптов, используйте текстовый редактор ASCII, чтобы открыть файл конфигурации Apache, httpd.conf.

Если вы используете Apache 1.x, файл находится в папке c:Program FilesApache GroupApacheconf. Пользователи Apache 2.0.x могут найти его в папке C:Program FilesApache GroupApache2conf, а пользователи Apache 2.2.x — в папке C:Program FilesApache Software FoundationApache2.2conf. Как правило, он находится в папке conf каталога, где установлен Apache.

Найдите раздел файла с операторами LoadModule. Объявления, перед которыми стоит символ хэша «#», считаются закомментированными.

Если используете Apache 1.x, добавьте следующую строку после всех операторов LoadModule:

LoadModule php5_module "c:/php/php5apache.dll"

Если вы используете Apache 2.0.x, добавьте следующую строку после всех операторов LoadModule:

LoadModule php5_module "c:/php/php5apache2.dll"

Если вы используете Apache 2.2.x, добавьте следующую строку:

LoadModule php5_module "c:/php/php5apache2_2.dll"

Обратите внимание, что в этом примере установки PHP используется символ прямой косой черты («/») вместо традиционной обратной косой черты Windows («»). Это не опечатка.

Если вы используете Apache 1.x, найдите серию операторов «AddModule» и добавьте после всех строк следующую.

Затем найдите в файле блок AddType и добавьте приведенную ниже строку после последнего оператора AddType. Это нужно сделать независимо от того, какую версию Apache вы используете. Для Apache 2.2.x нужно найти строки AddType в разделе <IfModule mime_module>. Добавьте строку непосредственно перед закрытием </ IfModule> для этого раздела.

AddType application/x-httpd-php .php

Если необходима поддержка других типов файлов, например «.phtml», добавьте их в список, например, так:

AddType application/x-httpd-php .phtml

Тем, кто использует одну из версий Apache 2, нужно указать местоположение ini-файла PHP. Добавьте следующую строку в конец httpd.conf.

Если вы использовали другой каталог, нужно будет изменить c:/php на правильный путь. Не забудьте применить косую черту («/»).

Если используете Apache 1, вы уже разместили файл php.ini в папке Windows или где-нибудь в PATH. Поэтому PHP должен будет найти его самостоятельно.

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

Процедура для этого при установке PHP 7 одинаковая как для Apache 1.x, так и для всех версий серии 2.x.

Найдите часть конфигурационного файла Apache, в которой находится раздел ScriptAlias. Добавьте приведенную ниже строку сразу после строки ScriptAlias для «cgi-bin». Если используете Apache 2.2.x, убедитесь, что строка расположена до закрытия </ IfModule> для раздела <IfModule alias_module>.

Обратите внимание: если вы установили PHP в другом месте, например c:Program Filesphp, нужно указать соответствующий путь вместо c:/php/ (например, c:Program Filesphp). Не забудьте, что здесь мы используем простую косую черту («/») вместо обратной косой черты Windows («»).

ScriptAlias /php/ "c:/php/"

Apache нужно настроить MIME тип PHP. Найдите блок комментариев AddType, поясняющий его использование, и добавьте следующую строку ниже него. Для Apache 2.2.x найдите строки AddType в разделе <IfModule mime_module>. Добавьте приведенную ниже строку непосредственно перед закрытием </IfModule> для этого раздела.

AddType application/x-httpd-php .php

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

AddType application/x-httpd-php .phtml

Затем вам нужно указать серверу выполнять исполняемый файл PHP каждый раз, когда он встречает скрипт PHP. Добавьте в файл следующий код, например, после блока комментариев, поясняющих «Action«.

Если вы используете Apache 2.2.x, то добавьте код сразу после инструкции AddType, описанной выше; в Apache 2.2.x нет блока комментариев «Action«.

Action application/x-httpd-php "/php/php-cgi.exe"

Примечание: часть «/php/» будет распознана как ScriptAlias, своего рода макрос, который будет расширен Apache до «c:/php/» (или «c:/Program Files/php/», если вы установили PHP там). Другими словами, не помещайте в эту директиву путь «c:/php/php.exe» или «c:/Program Files/php/php.exe», а используйте «/php/php-cgi.exe».

Если используете Apache 2.2.x, найдите следующий раздел в файле httpd.conf:

<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>

Добавьте приведенные ниже строки сразу после раздела, который только что нашли.

<Directory "C:/php">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>

c) Настройка индексной страницы по умолчанию

Этот раздел относится к варианту установки PHP на Windows в качестве модуля Apache, так и двоичного CGI.

Если вы создаете файл index.php и хотите, чтобы Apache загружал его как главную страницу сайта, придется добавить еще одну строку в файл httpd.conf. Найдите строку, которая начинается с «DirectoryIndex», и добавьте «index.php» в список файлов. Например, если у вас был такой код:

DirectoryIndex index.html

измените его на:

DirectoryIndex index.php index.html

При следующем входе на веб-сервер через имя каталога, например «localhost» или «localhost/directory/», Apache отправит все скрипты из index.php или содержимое файла index.html, если index.php недоступен.

Перезагрузите сервер Apache. Это необходимо, чтобы Apache считал новые директивы конфигурации PHP, которые вы поместили в файл httpd.conf. Сервер Apache 2.2 можно перезапустить, дважды кликнув по иконке Apache Service Monitor в панели задач и нажав в появившемся окне кнопку «Перезапустить».

После установки PHP 5 5 или другой версии языка создайте php-файл со следующей строкой:

Сохраните в каталог Apache htdocs файл с именем test.php. Если используете «Блокнот», не забудьте сохранить имя «test.php» с кавычками. Иначе программа самостоятельно добавит расширение .txt.

Откройте данный файл в браузере, введя в адресную строку «localhost / test.php» (без кавычек). Не открывайте файл напрямую через проводник — вы увидите только код, введенный ранее. Вам нужно использовать указанный выше URL-адрес, чтобы браузер попытался получить доступ к веб-серверу Apache, который запускает PHP для интерпретации скрипта.

Если все пройдет успешно, вы увидите страницу с информацией о настройке PHP. Поздравляю — вы успешно установили PHP и настроили Apache для работы с ним. Вы можете загрузить этот же файл test.php на свой хостинг и запустить его там, чтобы узнать, как хостинг настроил PHP у себя, и попытаться воспроизвести эти настройки на своей машине.

Если это не сработает, проверьте, не выдает ли установка PHP или установка Apache ошибок. Для этого откройте окно командной строки и запустите php-cgi.exe для файла test.php, например, c:phpphp-cgi test.php.

Если вы вызвали PHP из командной строки и увидели большой HTML-файл со всей информацией о конфигурации PHP, значит, PHP настроен правильно. Вероятно, проблема связана с конфигурацией Apache. Убедитесь, что вы перезапустили Apache после внесения изменений в конфигурацию и что вы правильно настроили веб-сервер.

Полное справочное руководство по установке PHP можно найти на официальном сайте технологии. Его можно посмотреть онлайн или загрузить для изучения в автономном режиме.

Хорошего всем дня!

Внимание! Данная инструкция служит дополнением к инструкции по установке Apache 2.4VC11 и PHP 5.6 и описывает лишь отличительные моменты, которые касаются установки Apache24 и PHP7 на Windows. Описание установки СУБД MySQL остается прежним и не повторяется в этой инструкции.

Данная инструкция рассчитана на разработчиков с базовыми знаниями Apache и PHP. В данной инструкции будут описана только разница в установке Apache и PHP с основной инструкцией по установке PHP 5.6. Если Вы не в курсе, что такое WEB-сервер, http-протокол и интерпретатор PHP, то Вы всегда можете узнать об этом более подробно, прочитав документацию.

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

Установка Apache 2.4 VC14
#

  1. Загружаем Apache 2.4 binaries VC14 под свою систему по ссылке http://www.apachelounge.com/download/ Качаем 64 разрядную версию сервера. На момент написания этих строк файл назывался так: httpd-2.4.17-win64-VC14.zip
  2. Если нужны какие-то дополнительные модули, их можно загрузить там же (для базовой установки нет необходимости)
  3. Загружаем и устанавливаем обновления Visual C++ Redistributable for Visual Studio 2015 с сайта Microsoft
  4. Разархивируем содержимое папки Apache24 из скаченного архива в D:USRapache. Обратите внимание, что в D:USRapache нужно положить не папку Apache24 из архива, а ее содержимое. Инсталлировать ничего не требуется
  5. В файле D:USRapacheconfhttpd.conf изменяем значение ServerRoot на “d:/USR/apache” (строка 37) и значение DocumentRootDirectory) на “d:/USR/www” (строки 243 и 244). Так же следует раскомментировать строку 219 и изменить ее на: ServerName localhost:80
  6. Изменяем параметры хранения логов в том же файле (находим параметры и изменяем):
    ErrorLog "D:/USR/log/apache-error.log"
    CustomLog "D:/USR/log/apache-access.log" common
    
  7. Устанавливаем сервис Apache. Открываем командную строку от имени Администратора и вставляем туда следующую строку:
    D:USRapachebinhttpd.exe -k install
    
  8. Следим за сообщениями об ошибках во время установки сервиса. Если все сделано верно, никаких ошибок быть не должно. Если у вас после выполнения строки не появилась снова командная строка, то вы что-то сделали неправильно. Просто воспользуйтесь функциями скопировать и вставить, чтобы не допускать ошибок при перепечатке
  9. Создаем на рабочем столе ярлык для D:USRapachebinApacheMonitor.exe и/или помещаем его в автозагрузку (для открытия окна автозагрузки в WIN8..10 необходимо нажать WIN+R, затем ввести shell:Startup и нажать ОК)
  10. Запускаем «ApacheMonitor». В системном трее появится ярлык. Нажимаем на него левой кнопкой, выбираем Apache24 -> Start
  11. В браузере заходим на http://localhost/ — должны увидеть It works!
  12. Если не увидели такой надписи, разбираемся, что пошло не так (читаем логи, гуглим, пытаемся самостоятельно разобраться с проблемой, раз уж решили разбираться в тонкостях работы веб-сервера)

Установка PHP 7
#

  1. Загружаем последнюю версию VC14 x64 Thread Safe по ссылке http://windows.php.net/download/. Обратите внимание, что нужен именно VC14 и именно Thread Safe. Файл, который Вам нужен, скорее всего будет называться наподобие: php-7.0.0-Win32-VC14-x64.zip
  2. Извлекаем содержимое архива в D:USRphp. Как в случае с Apache, инсталлировать ничего не требуется
  3. В файл D:USRapacheconfhttpd.conf добавляем строки:
    LoadModule php7_module "d:/USR/php/php7apache2_4.dll"
    AddHandler application/x-httpd-php .php
    # Путь к файлу php.ini
    PHPIniDir "D:/USR/php"
    
  4. И изменяем значение параметра DirectoryIndex на index.html index.php (строка 278)
  5. Используя «ApacheMonitor» перезапускаем Apache (Apache24 -> Restart)
  6. Заходим браузером http://localhost/index.php и убеждаемся, что PHP работает (обратитесь к первоначальной статье, чтобы узнать, откуда берется файл index.php) — в браузере будет вывод PhpInfo
  7. Делаем копию шаблона конфигурационного файла D:USRphpphp.ini-development с именем D:USRphpphp.ini — это конфигурационный файл для РНР.
  8. Редактируем конфигурационный файл D:USRphpphp.ini. Пользуясь поиском находим внутри файла, раскомментируем и изменяем параметры. Обратите внимание, что параметр extension определяет набор расширений РНР. Раскомментируйте те расширения, которые нужны Вам. В примере расширения, которые были нужны мне. Временную зону указывайте свою, а не мою:
    extension_dir = "D:/USR/php/ext"
    sys_temp_dir = "D:/USR/tmp"
    extension=php_curl.dll
    extension=php_gd2.dll
    extension=php_gettext.dll
    extension=php_mbstring.dll
    extension=php_mysqli.dll
    extension=php_openssl.dll
    date.timezone = Europe/Zaporozhye
    

    Если у Вас возникли проблемы с запуском curl, обратитесь к этой инструкции.

  9. Выполняем в командной строке php -m чтобы просмотреть список подключенных расширений.
  10. Перезапускаем Apache используя «ApacheMonitor»

Установка и настройка всего остального не изменилась. Обратитесь пожалуйста к статье по установке PHP 5.6 для получения подробной информации.

image

Доброго времени суток, уважаемые читатели. В этой статье я хочу поделиться с вами личным опытом настройки Apache под Windows 8.1 x64.
Было время – установил я себе Windows 8.1 и думаю, раз уж пошло на то, «дай ка» Я и Apache подниму! И как обычно меня он очень порадовал (табличка: «Сарказм»). Пришлось повозиться почти целую ночь, чтобы поднять сервер. И мне это удалось! После этого я решил тем самым написать небольшую статью по настройке Apache, чтобы другой человек не тратил на это столько же времени, сколько Я.
После нескольких минут раздумий, решил написать пошаговую инструкцию, которая будет состоять из нескольких разделов:

  1. Подготовка папок
  2. Настройка Apache
  3. Настройка PHP
  4. Настройка MySQL
  5. Устанавливаем phpMyAdmin

Ну что ж, приступим.

Подготовка папок

Я очень не люблю, чтобы у меня все валялось, где попало, так что для начала создадим папки, где у нас будут располагаться программы и сайты.
Создадим на диске «C:» (или где вам удобней) папку «Server»:
C:Server
В ней создадим 2 папки:
C:Serverweb – это папка в которой у нас будут лежать программы
C:Serverdomains – а в этой папке будут лежать наши сайты
Итак, в папке web мы создадим 3 папки для apache, php, mysql:
C:Serverwebapache
C:Serverwebphp
C:Serverwebmysql
Далее перейдем в папку domains и создадим папку localhost
C:Serverdomainslocalhost
Внутри папки у нас будет 2 подпапки: public_html – для файлов сайта; logs – для текстовых файлов, в которых записывается «кто» получал доступ к сайту и какие ошибки в работе сайта появлялись.
C:Serverdomainslocalhostpublic_html
C:Serverdomainslocalhostlogs
На этом структура папок заканчивается, переходим к настройке Apache.

Настройка Apache

Для установки Apache нам понадобиться сам Apache (Кэп). Так как у нас Windows 8.1 x64, то устанавливать будем Apache x64.
Для скачивания перейдем по ссылке:
www.apachelounge.com/download/win64
и скачиваем «httpd-2.4.6-win64.zip». Так же нам понадобиться для нормальной работы «Распространяемый пакет Microsoft Visual C++ 2010 (x64)». Для этого скачаем его по этой ссылке:
www.microsoft.com/ru-ru/download/details.aspx?id=14632
и устанавливаем.
После того как скачался наш архив с Apache, откроем его. Открыв архив, мы увидим папку «Apache24», зайдем в нее. Появиться множество папок и файлов программы, все распаковываем в заготовленную ранее папку:
C:Serverwebapache
Должно получиться так:
C:Serverwebapachebin
C:Serverwebapachecgi-bin
C:Serverwebapacheconf
C:Serverwebapacheerror
C:Serverwebapachehtdocs
C:Serverwebapacheicons
C:Serverwebapacheinclude
C:Serverwebapachelib
C:Serverwebapachelogs
C:Serverwebapachemanual
C:Serverwebapachemodules
Папки, такие как cgi-bin, htdocs, icons и manual нам не нужны – можете их удалить.
Перейдем в папку:
C:Serverwebapacheconf
И откроем файл конфигурации Apache – «httpd.conf» любым текстовым редактором. В этом файле каждая строка содержит директивы для настройки Apache, а строки, начинающиеся со знака # (решетка) – комментарий и пояснение. Приступим к настройке:

Файл конфигурации Apache

# директива Apache
ServerRoot “C:/Server/web/apache”
# Слушаем на локальном IP порт (80 по стандарту)
Listen 127.0.0.1:80
# далее подключим библиотеки расширений для Apache
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module "C:/Server/web/php/php5apache2_4.dll"
# указываем Apache, что файлы с расширением php, нужно воспринимать как php-скрипты
AddHandler application/x-httpd-php .php
# укажем расположение файла настроек php
PHPIniDir “C:/Server/web/php”
# изменим имя сервера
ServerName 127.0.0.1:80
# изменим доступ к директории
<Directory />
Options Includes Indexes FollowSymLinks
AllowOverride All
Allow from all

# директория с нашими сайтами
DocumentRoot “C:/Server/domains”
# индексные файлы, по приоритету.
<IfModule dir_module>
DirectoryIndex index.php index.html index.htm index.shtml

# папка для log-файлов
ErrorLog “C:/Server/domains/logs/error.log”
CustomLog “C:/Server/domains/logs/access.log”
# добавим alias для phpMyAdmin, и поправим alias для cgi
<IfModule alias_module>
Alias /pma “C:/Server/domains/phpMyAdmin”
ScriptAlias /cgi-bin/ “C:/Server/web/apache/cgi-bin/”

# правим путь для cgi
<Directory “C:/Server/web/apache/cgi-bin”>
AllowOverride None
Options None
Require all granted

# типы файлов
<IfModule mime_module>

AddType text/html .shtml
AddOutputFilter INCLUDES .shtml
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

# Другие конфиги:
Include conf/extra/httpd-mpm.conf
Include conf/extra/httpd-autoindex.conf
Include conf/extra/httpd-vhosts.conf
Include conf/extra/httpd-manual.conf
Include conf/extra/httpd-default.conf
<IfModule setenvif_module>
BrowserMatch "MSIE 10.0;" bad_DNT

<IfModule headers_module>
RequestHeader unset DNT env=bad_DNT

На этом заканчивается настройка httpd.conf.
В конфигурационном файле Apache httpd.conf были подключены дополнительные конфиги:
Include conf/extra/httpd-mpm.conf
Include conf/extra/httpd-autoindex.conf
Include conf/extra/httpd-vhosts.conf
Include conf/extra/httpd-manual.conf
Include conf/extra/httpd-default.conf
Откроем файл «C:Serverwebapacheconfextrahttpd-mpm.conf» и быстро пробежимся по нему.
# указываем, где у нас будет храниться pid-файл:
<IfModule !mpm_netware_module>
PidFile “C:/Server/web/apache/logs/httpd.pid”

Остальные параметры оставляем без изменений. Откроем файл «httpd-autoindex.conf», изменим там только строки с путем:
Alias /icons/ "c:/Server/web/apache/icons/"
<Directory "C:/Server/web/apache/icons">
Options Indexes MultiViews
AllowOverride None
Require all granted

Далее переходим к файлу «httpd-vhosts.conf», удаляем его содержимое. После того, как мы это сделали, начинаем наполнять его заново:

Файл хостов Apache

# на примере доменная localhost
<VirtualHost localhost:80>
DocumentRoot "C:/Server/domains/localhost/public_html"
ServerName localhost
ErrorLog "C:/Server/domains/localhost/logs/error.log"
CustomLog "C:/Server/domains/localhost/logs/access.log" common

# добавим для будущего phpMyAdmin (не забываем создать папку)
<VirtualHost phpmyadmin:80>
DocumentRoot "C:/Server/domains/phpmyadmin/public_html"
ServerName localhost
ErrorLog "C:/Server/domains/phpmyadmin/logs/error.log"
CustomLog "C:/Server/domains/phpmyadmin/logs/access.log" common

На этом редактирование файла заканчивается. Далее в оставшихся файлах правим только пути:
Файл «httpd-manual.conf»:
AliasMatch ^/manual(?:/(?:da|de|en|es|fr|ja|ko|pt-br|ru|tr|zh-cn))?(/.*)?$ "C:/Server/web/apache/manual$1"
<Directory "C:/Server/web/apache/manual">
В файле «httpd-default.conf» никаких изменений не производиться. На этом настройка конфигурации Apache завершается.

Настройка PHP

Раз у нас Windows 8.1 x64 и Apache x64 установлен и настроен, то и php должно быть x64.
Идем на сайт:
www.anindya.com/tag/php
и скачиваем архив php последней версии. Нам нужен php как модуль, т.е. для этого скачиваем Thread Safe. После того как архив скачался, открываем его и переносим содержимое в папку «C:Serverwebphp». Создадим две пустые папки «tmp» и «upload». Далее в этой папке ищем файл «php.ini-development» и переименовываем его в «php.ini». Открываем файл в текстовом редакторе и изменяем директивы (комментирования строк в файле начинается с точки с запятой).

Настройка php.ini

short_open_tag = On
zlib.output_compression = On
post_max_size = 64M
include_path = ".;С:Serverwebphpincludes"
extension_dir = "C:/Server/web/php/ext"
upload_tmp_dir = "C:/Server/web/php/upload"
upload_max_filesize = 64M
extension=php_bz2.dll
extension=php_curl.dll
extension=php_gd2.dll
extension=php_mbstring.dll
extension=php_mysql.dll
extension=php_mysqli.dll
extension=php_pdo_mysql.dll
extension=php_sockets.dll
extension=php_sqlite3.dll
; в секции [Date] указываем временную зону нашего сервера (http://php.net/date.timezone)
date.timezone = "Asia/Yekaterinburg"
session.save_path = "С:/Server/web/php/tmp/"

На этом настройка php заканчивается.

Настройка MySQL

Ставим MySQL x64 как сокет под windows. Скачиваем архив с последней версией MySQL x64:
dev.mysql.com/downloads/mysql
В низу страницы находим Windows (x86, 64-bit), ZIP Archive и жмем на кнопку «Download». Вам перекинет на страницу регистрации на сайте. Нажимаем внизу страницы «No thanks, just start my download», запуститься скачивание архива MySQL. После того как скачался архив откроем его и перенесем все содержимое папки в «C:Serverwebmysql»
Теперь открываем файл настроек MySQL – «C:Serverwebmysqlmy-default.ini». Удаляем все его содержимое и вносим туда свои данные.
[client]
port=3306
host=127.0.0.1
[mysqld]
port=3306
bind-address=127.0.0.1
enable-named-pipe
basedir="C:/Server/web/mysql/"
datadir="C:/Server/web/mysql/data/"
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
Вот и всё. В конфигурационном файле мы указали, что скрипты могут обращаться к серверу и по локальному IP, и по сокет-соединению.
Осталось дело за малым. Добавим в системную переменную «PATH» пути к Apache и MySQL, для этого:

  1. Перетащите курсор мыши в правый нижний угол экрана
  2. Щелкните на значке «Поиск» и введите: панель управления
  3. Выберите System (Система)-> Advanced (Дополнительные параметры системы)
  4. Выберите Environment Variables (Переменные среды), в меню System Variables (Системные переменные), найдите переменную PATH и щелкните на ней.
  5. Пропишите пути к Apache и MySQL:

;C:Serverwebapachebin;C:Serverwebmysqlbin
Далее установим службы Apache и MySQL. Для этого воспользуемся сочетанием клавиш «Win+X», появиться выпадающее меню в левом нижнем углу. Выберем «Командная строка (администратор)».
В командной строке вводим, для установки Apache:
httpd –k install
для установки MySQL:
mysqld.exe --install MySQL --defaults-file=”C:Serverwebmysqlmy-default.ini”
Установим пароль для MySQL-пользователя. Для этого запустим службу MySQL командой:
NET start MySQL
После того как служба запустилась, установим пароль:
mysqladmin –u root password ВашПароль
В файл «httpd-vhosts.conf» мы прописали два сайта, для того чтобы браузер мог их увидеть, названия сайтов нужно добавить в файла «hosts». Перейдем в папку:
C:WindowsSystem32Driversetc
откроем файл «hosts» любым текстовым редактором (запустить от имени администратора) и в конец файла добавим:
127.0.0.1 localhost
127.0.0.1 phpmyadmin
Сохраняем файл.
Для удобства запуска и остановки служб Apache и MySQL создадим файлы start-server.bat и stop-server.bat.
Для этого перейдем в папку «C:Server» и создадим два этих файла.
Содержание «start-server.bat»:
@echo off
NET start Apache2.4
NET start MySQL
Содержание «stop-server.bat»:
@echo off
NET stop Apache2.4
NET stop MySQL
Настройка Apache, PHP и MySQL на этом закончена. Для того чтобы протестировать сервер, давайте в папке «C:Serverdomainslocalhostpublic_html» создадим файл «index.php» с содержимым:

<?php
    echo phpinfo();

Далее запустим наш сервер, для этого запустите «start-server.bat» от имени администратора. После того как сервер запустился, откройте браузер и введите в адресной строке «localhost».
Должна отобразиться страница с информацией о PHP.

Устанавливаем PhpMyAdmin

Скачиваем последнюю версию PhpMyAdmin отсюда:
www.phpmyadmin.net/home_page/index.php
Открываем скаченный архив и переносим содержимое его папки в папку для нашего домена «C:Serverdomainsphpmyadminpublic_html».
Находим файл «config.sample.inc.php», делаем его копию и переименовываем копию в «config.inc.php». Открываем файл текстовым редактором и меняем данные:

<?php
// Желательно сменить секретный код
$cfg['blowfish_secret'] = 'a8b7c6d';
$i = 0;
$i++;
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
?>

Сохраняем и закрываем файл. Открываем в браузере сайт «http://phpmyadmin» и наслаждаемся.

Статья получилась объемная, но надеюсь полезная.

Этот раздел содержит инструкции по установке PHP для Apache 2.x
на системы Microsoft Windows. Мы также имеем инструкции для
пользователей Apache 1.3.x на отдельной странице.

Замечание:

Сначала вам необходимо прочитать пошаговое
руководство по установке

Замечание:
Поддержка Apache 2.2

Пользователям Apache 2.2 следует обратить внимание на то, что DLL файл для Apache 2.2 называется
php5apache2_2.dll, а не php5apache2.dll
и он доступен только для PHP 5.2.0 и более поздних версий.

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

Apache 2.x предназначен для работы в серверных версиях Windows,
таких как Windows NT 4.0, Windows 2000, Windows XP или Windows 7.
Хотя Apache 2.x может использоваться на Windows 9x, эти
платформы не поддерживаются полностью, и некоторые функции не будут работать
правильно. Исправление этой ситуации не планируется.

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

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

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

Установка PHP как обработчика под Apache

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

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

#
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler application/x-httpd-php .php

# конфигурирование пути к php.ini
PHPIniDir "C:/php"

Замечание:

Не забудьте указать актуальный путь к директории PHP вместо
C:/php/ в приведенном примере. Позаботьтесь, чтобы
в директиве LoadModule использовались либо php5apache2.dll либо
php5apache2_2.dll и удостоверьтесь, что указанный файл
фактически находится по пути, который вы указали в директиве.

Приведенная выше конфигурация позволит PHP обработать любой файл, который имеет
расширение .php, даже если имеются другие расширения. К примеру, файл с именем
example.php.txt будет запущен обработчиком PHP. Чтобы гарантировать,
что только файлы, которые имеют расширение.php
будут запущены, используйте следующую конфигурацию:

<FilesMatch .php$>
      SetHandler application/x-httpd-php
 </FilesMatch>

Запуск PHP как CGI

Вы должны обратиться к документации » Apache CGI
для более полного понимания о запуске CGI под Apache.

Для запуска PHP как CGI, вам необходимо поместить ваши php-cgi файлы в
директорию, обозначенную как директория CGI, используя директиву ScriptAlilas.

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

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

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

Внимание

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

Запуск PHP под FastCGI

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

Получить mod_fcgid здесь:
» http://httpd.apache.org/mod_fcgid/.
исполняемые файлы под Win32 доступны для скачивания с этого сайта. Установите модуль
в соответствии с прилагаемыми инструкциями.

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

Пример #3 Конфигурация Apache для запуска PHP как FastCGI

LoadModule fcgid_module modules/mod_fcgid.so  

# Где находится ваш php.ini?
FcgidInitialEnv PHPRC        "c:/php"

AddHandler fcgid-script .php  
FcgidWrapper "c:/php/php-cgi.exe" .php  

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

Вернуться к: Установка в системах Windows

PHP is a Hypertext Preprocessor, earlier it known as Personal Home Page. It is an open-source server (available for free) side scripting language (everything is implemented on the webserver) that is embedded into HTML and used for web development. PHP script starts with <?PHP and ends with?>. Some common features of PHP are:

  • Open Source
  • Platform Independent
  • Used to create dynamic web pages
  • Provides Security encryption
  • Cost-Efficient
  • Compatibility
  • Website function faster

Facebook, Wikipedia, WordPress, Tumbler, and yahoo are some of the major companies using PHP

Why PHP on Apache?

PHP and MySQL both are compatible with an Apache server. These two are open source and easy to set up. PHP runs on many platforms like Windows, Linux, and Unix. Because of these advantages, PHP is used on Apache servers. Before installing the PHP make sure that the Apache server is already installed on your PC. 

How to Install PHP on Apache?

Follow the steps below in order to set up PHP on Apache without facing any difficulties.

Step 1: Visit the official website of PHP. Here you will find the two different packages called Non-Thread Safe and Thread Safe Packages. Download the zip folder under the Thread Safe section because we are working on Apache.

 Visit-the-official-website-of-PHP

Step 2: Extract the files and rename the extracted file to PHP8.1(It’s completely on the user’s wish) and move to the directory where the Apache folder is located. Add the path to the system variables. To add the copied address to the system variables, search for Control Panel > System & Security > System > advanced system settings > Environment variables > System Variables > Path > Edit > New and paste the copied address.

Extract-the-files

Note: Make sure that both Apache and PHP extracted files should be in the same folder

Step 3: To check whether the PHP directory is added to the path of system variables or not. Open PowerShell as an administrator. Change PowerShell mode to the command prompt by entering the command cmd. Then type path hit enter if the directory path is visible on the screen, then the path is successfully added to the system variables. To know the version of the PHP type php -v and then hit enter

Check-whether-the-PHP-directory-is-added-to-the-path-of-system-variables-or-not

Step 4: Now it’s time to configure Apache for this open C: > Apache24 > conf > httpd.conf

Configure-Apache

Scroll down the httpd.conf file to the end and write the below three lines. In Apache, PHP is loaded as a module so load the module using  LoadModule, read PHP files with the file handler and finally add the PHP file located address within the double quotes

LoadModule php_module “C:PHP8.1php8apache2_4.dll”  

AddHandler application/x-httpd-php  .php

PHPIniDir “C:PHP8.1”

Add-the-PHP-file-located-address

Step 5: In the PHP8.1 directory there are two default configuration files “php.ini-development” and “php.ini-production. Copy-paste the “php.ini-development” and rename the copied file as “php.ini”

Rename-the-copied-file

Step 6: Set ServerName parameter as localhost for this search (Ctrl+F) “ServerName” in “httpd.conf” file and set ServerName as localhost below the “#ServerName www.example.com:80” line ServerName localhost

Set-ServerName-parameter-as-localhost

Step 7: Open PowerShell in command prompt mode as an administrator and type “httpd –t” and hit enter. If everything is ok then it displays “Syntax OK”

Open PowerShell-in-command-prompt-mode

Step 8: Specify the default PHP page. For this search for ” DirectoryIndex ” in httpd.conf file. Inside Dir-module add “index.php”

Specify-the-default-PHP-page

Step 9: Open htdocs folder which is present inside the Apache24 folder and create a PHP file with the below code and save it as index.php (users wish) for testing. To test the program, open your favorite browser and then type localhost and hit enter.

PHP CODE :

<?php

phpinfo();

?>

Running PHP code on Apache server

Now Apache server is ready to run PHP codes. Let’s understand how to run the first PHP code on the Apache server. For this open an editor write an example PHP code and save it in Apache24 > htdocs > projectfolder > filename.php. 

Php-code

a projectfolder is your folder with your projectname and filename.php  is your filename which should store inside your projectfolder. Now it’s time to run the example program. For this open your favorite browser and then type “localhost/projectfolder/filename.php”. then it will show the below output

Final-output

PHP is a Hypertext Preprocessor, earlier it known as Personal Home Page. It is an open-source server (available for free) side scripting language (everything is implemented on the webserver) that is embedded into HTML and used for web development. PHP script starts with <?PHP and ends with?>. Some common features of PHP are:

  • Open Source
  • Platform Independent
  • Used to create dynamic web pages
  • Provides Security encryption
  • Cost-Efficient
  • Compatibility
  • Website function faster

Facebook, Wikipedia, WordPress, Tumbler, and yahoo are some of the major companies using PHP

Why PHP on Apache?

PHP and MySQL both are compatible with an Apache server. These two are open source and easy to set up. PHP runs on many platforms like Windows, Linux, and Unix. Because of these advantages, PHP is used on Apache servers. Before installing the PHP make sure that the Apache server is already installed on your PC. 

How to Install PHP on Apache?

Follow the steps below in order to set up PHP on Apache without facing any difficulties.

Step 1: Visit the official website of PHP. Here you will find the two different packages called Non-Thread Safe and Thread Safe Packages. Download the zip folder under the Thread Safe section because we are working on Apache.

 Visit-the-official-website-of-PHP

Step 2: Extract the files and rename the extracted file to PHP8.1(It’s completely on the user’s wish) and move to the directory where the Apache folder is located. Add the path to the system variables. To add the copied address to the system variables, search for Control Panel > System & Security > System > advanced system settings > Environment variables > System Variables > Path > Edit > New and paste the copied address.

Extract-the-files

Note: Make sure that both Apache and PHP extracted files should be in the same folder

Step 3: To check whether the PHP directory is added to the path of system variables or not. Open PowerShell as an administrator. Change PowerShell mode to the command prompt by entering the command cmd. Then type path hit enter if the directory path is visible on the screen, then the path is successfully added to the system variables. To know the version of the PHP type php -v and then hit enter

Check-whether-the-PHP-directory-is-added-to-the-path-of-system-variables-or-not

Step 4: Now it’s time to configure Apache for this open C: > Apache24 > conf > httpd.conf

Configure-Apache

Scroll down the httpd.conf file to the end and write the below three lines. In Apache, PHP is loaded as a module so load the module using  LoadModule, read PHP files with the file handler and finally add the PHP file located address within the double quotes

LoadModule php_module “C:PHP8.1php8apache2_4.dll”  

AddHandler application/x-httpd-php  .php

PHPIniDir “C:PHP8.1”

Add-the-PHP-file-located-address

Step 5: In the PHP8.1 directory there are two default configuration files “php.ini-development” and “php.ini-production. Copy-paste the “php.ini-development” and rename the copied file as “php.ini”

Rename-the-copied-file

Step 6: Set ServerName parameter as localhost for this search (Ctrl+F) “ServerName” in “httpd.conf” file and set ServerName as localhost below the “#ServerName www.example.com:80” line ServerName localhost

Set-ServerName-parameter-as-localhost

Step 7: Open PowerShell in command prompt mode as an administrator and type “httpd –t” and hit enter. If everything is ok then it displays “Syntax OK”

Open PowerShell-in-command-prompt-mode

Step 8: Specify the default PHP page. For this search for ” DirectoryIndex ” in httpd.conf file. Inside Dir-module add “index.php”

Specify-the-default-PHP-page

Step 9: Open htdocs folder which is present inside the Apache24 folder and create a PHP file with the below code and save it as index.php (users wish) for testing. To test the program, open your favorite browser and then type localhost and hit enter.

PHP CODE :

<?php

phpinfo();

?>

Running PHP code on Apache server

Now Apache server is ready to run PHP codes. Let’s understand how to run the first PHP code on the Apache server. For this open an editor write an example PHP code and save it in Apache24 > htdocs > projectfolder > filename.php. 

Php-code

a projectfolder is your folder with your projectname and filename.php  is your filename which should store inside your projectfolder. Now it’s time to run the example program. For this open your favorite browser and then type “localhost/projectfolder/filename.php”. then it will show the below output

Final-output

Понравилась статья? Поделить с друзьями:
  • Как mdr перевести в gpt при установке windows
  • Как linux mint ввести в домен windows
  • Как jfif перевести в jpg на компьютере windows 10
  • Как iis включить в компонентах windows
  • Как dmg перевести в iso в windows