Setting up php on apache windows

This section contains notes and hints specific to Apache 2.x installs of PHP on Microsoft Windows systems.

This section contains notes and hints specific to Apache 2.x installs
of PHP on Microsoft Windows systems.

Note:

Please read the manual
installation steps first!

It is strongly recommended to consult the
» Apache Documentation
to get have a basic understanding of the Apache 2.x Server.
Also consider reading the
» Windows specific notes
for Apache 2.x before reading on here.

Download the most recent version of
» Apache 2.x
and a fitting PHP version. Follow the
Manual Installation Steps
and come back to go on with the integration of PHP and Apache.

There are three ways to set up PHP to work with Apache 2.x on Windows.
PHP can be run as a handler, as a CGI, or under FastCGI.

Note: Remember that when adding
path values in the Apache configuration files on Windows, all backslashes
such as c:directoryfile.ext should be converted to
forward slashes: c:/directory/file.ext. A trailing
slash may also be necessary for directories.

Installing as an Apache handler

To load the PHP module for Apache 2.x, the following lines in the
Apache httpd.conf configuration file must be inserted:

Example #1 PHP and Apache 2.x as handler

# before PHP 8.0.0 the name of the module was php7_module
LoadModule php_module "c:/php/php8apache2_4.dll"
<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>
# configure the path to php.ini
PHPIniDir "C:/php"

Note:

The actual path to PHP must be substituted instead of
C:/php/ in the above examples.
Make sure that the file referenced in the LoadModule directive is at
the specified location. Use php7apache2_4.dll
for PHP 7, or php8apache2_4.dll for PHP 8.

Running PHP as CGI

It is strongly recommended to consult the
» Apache CGI documentation
for a more complete understanding of running CGI on Apache.

To run PHP as CGI, the php-cgi files will need to be placed in a
directory designated as a CGI directory using the ScriptAlias directive.

A #! line will need to be placed in the PHP files,
which point to the location of the PHP binary:

Example #2 PHP and Apache 2.x as CGI

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

Warning

A server deployed in CGI mode is open
to several possible vulnerabilities. Please read our
CGI security section to learn how to
defend yourself from such attacks.

Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a
CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from
» https://www.apachelounge.com.
Win32 binaries are available for download from that site.
Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths
to reflect your how you have installed things on your particular system:

Example #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so
# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php"
<FilesMatch .php$>
    SetHandler fcgid-script
</FilesMatch>
FcgidWrapper "c:/php/php-cgi.exe" .php

Files with a .php extension will now be executed by the PHP FastCGI
wrapper.

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

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

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

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

Contents:

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

Why PHP?

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

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

Why Install PHP Locally?

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

Alternative Installation Options

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

Using an all-in-one package

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

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

Using a Linux virtual machine

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

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

Using Windows Subsystem for Linux 2

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

Using Docker

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

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

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

Installing Apache (optional)

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

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

cd myproject
php -S localhost:8000

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

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

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

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

cd C:Apache24bin
httpd

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

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

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

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

Installing PHP

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

Step 1: Download the PHP files

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

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

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

Step 3: Configure php.ini

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

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

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

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

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

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

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

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

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

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

PHP path environment variable

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

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

Step 5: Configure PHP as an Apache module

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

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

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

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

Change it to:

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

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

cd C:Apache24bin
httpd -t

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

If all went well, start Apache with httpd.

Step 6: Test a PHP file

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

<?php
phpinfo();
?>

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

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

Further information:

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

Best of luck!

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

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

Оглавление

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

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

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

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

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

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

Заключение


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Меняем

Define SRVROOT "c:/Apache24"

на

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

меняем

#ServerName www.example.com:80

на

ServerName localhost

меняем

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

на

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

меняем

DirectoryIndex index.html

на

DirectoryIndex index.php index.html index.htm

меняем

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

на

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

и меняем

#LoadModule rewrite_module modules/mod_rewrite.so

на

LoadModule rewrite_module modules/mod_rewrite.so

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

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

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

c:ServerbinApache24binhttpd.exe -k install

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

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

c:ServerbinApache24binhttpd.exe -k start

И нажмите Enter.

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

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

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

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

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

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

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

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

c:ServerbinApache24binhttpd.exe -k restart

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

<?php
phpinfo ();

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

Настройка PHP 8

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

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

;extension_dir = "ext"

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

extension_dir = "C:ServerbinPHPext"

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

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

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

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

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

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

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

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

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

c:ServerbinApache24binhttpd.exe -k restart

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

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

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

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

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

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

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

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

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

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

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

Setup Apache, PHP & MySql on Windows 10

Setup Apache

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

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

Setup Apache, PHP & MySql on Windows 10

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

Define SRVROOT "F:/localserver/Apache24"

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

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

Setup Apache, PHP & MySql on Windows 10

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

Setup Apache, PHP & MySql on Windows 10

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

Setup Apache, PHP & MySql on Windows 10


Setup PHP

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

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

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

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

Setup Apache, PHP & MySql on Windows 10

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

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

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

Setup Apache, PHP & MySql on Windows 10


Setup MySQL Server

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

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

Step 11: Setup the root password.

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually

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

MySql Server Setup Manually


Setup phpMyAdmin

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

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

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

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

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

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

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

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

Everything ready, Now time to check our phpmyadmin.

phpMyAdmin setup with MySql Server Manually

Conclusion

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

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

Buy Me a Coffee

Setting Php file on Windows

Developers can easily run or test their scripts in Windows before they put them out on the Internet, if they have Apache and PHP installed on their systems. This article is a tutorial on how Apache and PHP can be set up in Windows.

Web servers are computers that are usually set up in a facility called a data centre. These servers are maintained and operated by hosting companies, to store websites, so that people can visit them on the Internet. The files stored on a Web server are read by browsers, which convert these files into images and text for viewing. Your browser communicates with the Web server to bring you information from the Internet. The purpose of Web servers is to serve files, as requested. A server can send the same file, or a different one, to hundreds of users at the same time.

Web server software
Web servers typically run two types of operating systems —Linux or Microsoft Windows. Most of the Web servers today operate on Linux and most websites are hosted by Linux servers. It is confusing that these software programs are also referred to as servers. So you must distinguish between servers that refer to hardware and those that refer to software. Web servers also run other software programs in the background. Such software is useful for creating websites.

Basically, the Web server software receives your request to access a Web page. It runs a few security checks on your HTTP request and takes you to the Web page requested. Depending on the page you have requested, the server may be asked to run a few extra modules while generating the document to serve you. It then serves you the document you requested. The process is an example of the client/server model. All computers that host websites must have Web server programs and Apache is one such program.

Figure 1 Visual C++ redistribution installation

Figure 1: Visual C++ redistribution installation step 1
Figure 2 Visual C++ redistribution installation step 2
Figure 2: Visual C++ redistribution installation step 2

An introduction to Apache
Apache is the most widely used Web server software. Developed and maintained by the Apache Software Foundation, it is open source software available for free. It can be highly customised to meet the needs of diverse environments through the use of extensions and modules. Most WordPress hosting providers use Apache as their Web server software.

The Apache HTTP server is software (or a program) that runs in the background under an appropriate operating system; it supports multi-tasking, and provides services to other applications that connect to it, such as client Web browsers. It was first developed to work with Linux/UNIX operating systems, but was later adapted to work under other systems, including Windows and Mac. The Apache binary running under UNIX is called HTTPd (short for HTTP daemon), and under win32 is called Apache.exe.

In this tutorial, we will install Apache and PHP in Windows in order to run your system as localhost (server).

The system prerequisites to do so are:

  • Download and install Visual C++ redistributable 2015
  • Download Apache24
  • Download PHP 5.6

Figure 3 Change in DirectoryIndex

Figure 3: Change in DirectoryIndex
Figure 4 Change in ServerName
Figure 4: Change in ServerName

Downloading and installing Visual C++ redistributable 2015
Let’s first install Visual C++ redistributable. The earlier packages like Visual C++ redistributable 2012 will give an error of a missing vcruntime140.dll file; so it would be better if the newer version, Visual C++ redistributable 2015, is installed, which will solve most of the issues. Most computers nowadays have it pre-installed. Nevertheless, I will lead readers through the step-by-step procedure of the installation.
First, download Visual C++ redistributable 2015 from the Windows official site.
Next, download the preferred version, i.e., if your system is 32-bit then download the x86 version, or download x64 for a 64-bit system. Proceed to install after the download is complete.

Installation wizard of Visual C++ redistributable 2015
Read the terms and conditions of the licence, click on the tick mark to accept these, and then click on Next.

Click on Close when the installation finishes.

Downloading and installing Apache
We can download the latest version of Apache from https://www.apachelounge.com/download/. Download it based on your system’s requirements (32-bit or 64-bit).
Extract it and put it in the C: folder.

Figure 5 Installation of Apache Services

Figure 5: Installation of Apache Services
Figure 6 Editing Enviornmental variables
Figure 6: Editing Enviornmental variables
Figure 7 Uncommenting Extension_dir
Figure 7: Uncommenting Extension_dir

Downloading and installing PHP
Download PHP from http://windows.php.net/download. In the dropdown, Binaries and Source Releases, there will be many versions of PHP. The latest release is PHP 7, but I strongly suggest that you download PHP 5.6 because it is more common and will be installed in most of the servers and by the hosting services providers. You can use PHP 7 in the future but, as of now, we are coding something so we can continue with the PHP 5.6 thread safe release.

Download the Zip file and unzip it. Place it in a newly created folder named PHP inside the C: drive.

Running Apache and PHP in your system as localhost
Let’s access the Apache24 folder that we moved to the C:drive earlier. Then, get into the conf folder and edit the httpd.conf file using Notepad or your favourite text editor.
Scroll down to the bottom of the file and add the following lines:

LoadModule PHP5_module “c:/PHP/PHP5apache2_4.dll”
Addhandler application/x-httpd-PHP .PHP
# configure the path to PHP.ini
PHPIniDir “C:/PHP”

Next, find DirectoryIndex (you can use Ctrl+f) and change index.html to index.php.
What we are doing here is telling Apache that the first file we need is a PHP file and not an HTML one. Save the changes.

Now, search for ServerName (Ctrl+f ). Initially, it is commented; so uncomment it. We are changing this because we will use it for our browser search. Instead of typing www.example.com:80 in the browser search box, we just type localhost.

Next, launch the command line tool by typing cmd in the search bar of Cortana. Before we start CMD, we need administrative privileges too. Hence, instead of hitting Enter, we will hit Shift+Ctrl+Enter (or right-click and select Run as administrator). Sometimes, to install specific software, we need to run this with administrative privileges.
Then, write the following script:

C:apache24binhttpd -k install

We now have to configure a number of environmental variables. To do that, right-click on the Windows button and click on System. Then, click on Advanced system settings. Inside the Advanced tab, down below there is a button called Environmental variables. Click on it and under System variables select Path. Click on Edit to add some variables. Inside the Edit environment variables window, click on New to create new variables and add the following:

  • C:PHP
  • C:Apache24
  • C:Apache24bin

Use the Move up or Move down button to keep them in order, just to be sure. Click OK and close the window.
We can now check whether the Apache settings are correct and if all the servers are set up properly by running the following command in CMD, under administrative privileges:

C:Apache24binhttpd -S

Some PHP settings have to be edited in order to tell Apache which PHP setting we need to have. Let’s access the PHP folder in the C: drive. Scroll down and search for the PHP.ini-development file and rename it PHP.ini.

Figure 8 Uncommenting mysql modules

Figure 8: Uncommenting mysql modules
Figure 9 Running Localhost
Figure 9: Running Localhost
Figure 10 Running index page of PHP
Figure 10: Running index page of PHP

Let’s open this file and uncomment a number of sections.
First search for extension_dir and uncomment extension_dir = “ext” by removing the semicolon.
To uncomment PHP modules, let’s search for PHP_mysql.dll. There we have to uncomment two extensions of my_sql, which are used along with PHP.
Save the changes.
Let’s go back into our command line and then to the root folder, as follows:

C:WindowsSystem32>cd .. && cd ..

To go back one folder, for instance, if we are in C: drive and want to access the PHP folder, type:

C:>cd PHP

Inside the folder, type the following command:

C:PHP>PHP -m

To see the list of all the modules that are loaded, I suggest you restart your system. Open your browser, and type localhost in the URL search bar.

If something like what’s seen in Figure 9 shows up, we have the confirmation that our servers are running fine because we can see the files inside the localhost index. To access the folder, go to the C: drive and open the Apache folder. Find a folder named htdocs and create a new file named info.PHP inside it. Then type the following:

<?PHP
PHPinfo();
?>

Again, go to your browser and type localhost/info.PHP in the URL search bar to get information about the PHP version. There lies all the information on the localhost, modules and everything that we just installed.

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 для совместной работы с 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 можно найти на официальном сайте технологии. Его можно посмотреть онлайн или загрузить для изучения в автономном режиме.

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

Понравилась статья? Поделить с друзьями:
  • Setpoint logitech windows 7 64 bit скачать
  • Setpoint logitech windows 10 что это
  • Sha 2 windows 7 скачать 2021
  • Sha 2 windows 7 как узнать
  • Sha 2 windows 7 как исправить