Apache + Perl + PHP3 + MySQL для Windows 9x

Установка MySQL


Сначала определимся: зачем же вообще нужны базы данных Web-программисту? Неужели не проще писать все самому? Ведь обычно объем данных не очень велик (если Вы только не пишите поисковую систему). Наш личный опыт таков: оказывается, стоит затратить какое-то время на изучение MySQL - это удивительно мощный инструмент, который сэкономит в будущем немало часов, потраченных на отладку "взбесившегося" скрипта.

Итак, Вы решили установить у себя на локальном Apache поддержку MySQL. Как ни странно, это даже во многом проще, чем заставить работать Perl. Прежде чем привести точные инструкции, хотелось бы уточнить два момента:

1.       Эта статья не претендует ни в коей мере на то, чтобы быть учебником по MySQL. Предполагается, что Вы уже знаете, как работать с этой базой данных. Максимум, что здесь описывается - это то, как заставить MySQL работать под Window 95/98.

2.       В дальнейшем будем считать, что Apache у Вас установлен именно там, где это рекомендовалось выше.

Что ж, приступим.

1.       Для начала запаситесь терпением и скачайте дистрибутив MySQL - mysql.zip. Как можно заметить, он довольно большой. Затем разверните его в любую удобную Вам директорию.

2.       Запустите setup.exe. Он спросит, действительно ли Вы хотите установить MySQL. После того, как Вы ответите утвердительно, файлы начнут копироваться в директорию c:/mysql, т.е. он даже не спросит Вас, куда устанавливать MySQL. Ничего страшного.

3.       Теперь, если Вы любите порядок, можете скопировать директорию c:/mysql в какое-нибудь более приличное место - например, f:/usr/local/. Только после этого строго следуйте указаниям в статье.

4.       Создайте в директории f:/usr/

такие два .bat-файла:

1.       server.bat:

2.       @echo off

3.       f:\usr\local\mysql\bin\mysqld.exe --basedir f:/usr/local/mysql




4.       f:\usr\local\apache\Apache.exe

5.       shutdown.bat:

6.       @echo off

7.       f:\usr\local\apache\Apache.exe -d f:\USR\LOCAL\APACHE -k shutdown

8.       "f:\usr\local\mysql\bin\mysqladmin.exe" -u root shutdown

Файл server.bat

Вы будете запускать, когда захотите "включить" Apache и одновременно MySQL (ясно, что бессмысленно запускать MySQL без сервера), а shutdown.bat - для завершения работы Apache и MySQL. Очень важно

завершать работу MySQL правильно - иначе могут быть испорчены таблицы баз данных. Собственно, для этого мы и сделали эти два .bat-файла. (Кстати говоря, в отличие от Apache, у MySQL нет своего окна - ее процесс можно увидеть, лишь нажав Ctrl+Alt+Del. Это еще одна причина существования shutdown.bat).

Теперь для удобства можно создать ярлыки на Рабочем столе для этих файлов. Рекомендуем также назначить этим ярлыкам "горячие" клавиши: например, для запуска сервера - Ctrl+Alt+A, а для завершения работы - Ctrl+Alt+S. Кроме того, лучше поставить у этих ярлыков параметры "Запускать свернутыми в значок". Все это сильно упростит жизнь в дальнейшем.

5.       Что ж, считайте, MySQL уже установлена. Осталось только создать базу данных. Для этого следует запустить f:/usr/local/mysql/bin/mysqladmin

с ключем create имя_базы. Например, если мы хотим создать базу testbase, нужно ввести:

6.       f:/usr/local/mysql/bin/mysqladmin create testbase

7.       Если Вы планируете использовать MySQL в скриптах на PHP, проверьте, раскомментирована ли в файле php3.ini

(расположенном в директории с PHP и в c:\windows) следующая строка:

8.       extension=php3_mysql.dll

Если в ее начале стоит точка с запятой, уберите ее - иначе PHP не сможет опознавать функции для работы с MySQL



Поздравляем - теперь можно работать! Если хотите, можете проверить работоспособность MySQL следующим скриптом на PHP3 (скажем, расположенном в f:/www/test.php3):

<?

Error_Reporting(1+2+4);

define("DBName","testbase");

define("HostName","localhost");

define("UserName","root");

define("Password","");

if(!mysql_connect(HostName,UserName,Password))

 { echo "Не могу соединиться с базой ".DBName."!<br>"; exit; }

// Создаем таблицу test. Если такая таблица уже есть, сообщение об ошибке будет

// подавлено, т.к. используется "@"

@mysql(DBName,"create table test(id int,a text)");

// Вставляем в таблицу 10 записей

for($i=0; $i<10; $i++)

 { $id=time();

   mysql(DBName,"insert into test(id,a) values($id,'Строка $i!')");

 }  

// Выводим все записи

$r=mysql(DBName,"select * from test");

for($i=0; $i<mysql_numrows($r); $i++)

 { $f=mysql_fetch_array($r);

   echo "$f[id] -> $f[a]<br>\n";

 }

 

?>

Обращаем Ваше внимание на макросы DBName, HostName, UserName и Password. DBName должен содержать имя базы данных. HostName - всегда localhost, ведь мы работаем на локальном компьютере. В макросе UserName проще всего подставлять root, который является собственником всех таблиц. При установке MySQL пользователю root не назначается пароль, так что макрос Password равен пустой строке.

Virtual Host examples for common setups

Base configuration

·         IP-based vhosts only

·         Name-based vhosts only

·         Mixed name-/IP-based vhosts

·         Port-based vhosts

Additional features

·         Using _default_ vhosts

·         Migrating a named-based vhost to an IP-based vhost



·         Using the ServerPath

directive

IP-based vhosts only

·         Setup 1: The server machine has two IP addresses (111.22.33.44

and 111.22.33.55) which resolve to the names server.domain.tld

and www.otherdomain.tld

respectively. The hostname www.domain.tld

is an alias (CNAME) for server.domain.tld

and will represent the main server.

Server configuration:

    ...

    Port 80

    DocumentRoot /www/domain

    ServerName www.domain.tld

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/otherdomain

    ServerName www.otherdomain.tld

    ...

    </VirtualHost>

   

www.otherdomain.tld can only be reached through the address 111.22.33.55, while www.domain.tld can only be reached through 111.22.33.44

(which represents our main server).

·         Setup 2: Same as setup 1, but we don't want to have a dedicated main server.

Server configuration:

    ...

    Port 80

    ServerName server.domain.tld

   

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/domain

    ServerName www.domain.tld

    ...

    </VirtualHost>

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/otherdomain

    ServerName www.otherdomain.tld

    ...

    </VirtualHost>

   

The main server can never catch a request, because all IP addresses of our machine are in use for IP-based virtual hosts (only localhost requests can hit the main server).

·         Setup 3: The server machine has two IP addresses (111.22.33.44

and 111.22.33.55) which resolve to the names server.domain.tld

and www-cache.domain.tld

respectively. The hostname www.domain.tld

is an alias (CNAME) for server.domain.tld

and will represent the main server. www-cache.domain.tld

will become our proxy-cache listening on port 8080, while the web server itself uses the default port 80.

Server configuration:



    ...

    Port 80

    Listen 111.22.33.44:80

    Listen 111.22.33.55:8080

    ServerName server.domain.tld

   

    <VirtualHost 111.22.33.44:80>

    DocumentRoot /www/domain

    ServerName www.domain.tld

    ...

    </VirtualHost>

    <VirtualHost 111.22.33.55:8080>

    ServerName www-cache.domain.tld

    ...

      <Directory proxy:>

      order deny,allow

      deny from all

      allow from 111.22.33

      </Directory>

    </VirtualHost>

   

The main server can never catch a request, because all IP addresses (apart from localhost) of our machine are in use for IP-based virtual hosts. The web server can only be reached on the first address through port 80 and the proxy only on the second address through port 8080.

Name-based vhosts only

·         Setup 1: The server machine has one IP address (111.22.33.44) which resolves to the name server.domain.tld. There are two aliases (CNAMEs) www.domain.tld

and www.sub.domain.tld

for the address 111.22.33.44.

Server configuration:

    ...

    Port 80

    ServerName server.domain.tld

    NameVirtualHost 111.22.33.44

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/domain

    ServerName www.domain.tld

    ...

    </VirtualHost>

   

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/subdomain

    ServerName www.sub.domain.tld

    ...

    </VirtualHost>

   

Apart from localhost

there are no unspecified addresses/ports, therefore the main server only serves localhost requests. Due to the fact that www.domain.tld has the highest priority it can be seen as the default or primary server.

·         Setup 2: The server machine has two IP addresses (111.22.33.44

and 111.22.33.55) which resolve to the names server1.domain.tld

and server2.domain.tld

respectively. The alias www.domain.tld

should be used for the main server which should also catch any unspecified addresses. We want to use a virtual host for the alias www.otherdomain.tld



and one virtual host should catch any request to hostnames of the form *.sub.domain.tld with www.sub.domain.tld as its server name. The address 111.22.33.55

should be used for the virtual hosts.

Server configuration:

    ...

    Port 80

    ServerName www.domain.tld

    DocumentRoot /www/domain

    NameVirtualHost 111.22.33.55

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/otherdomain

    ServerName www.otherdomain.tld

    ...

    </VirtualHost>

  

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/subdomain

    ServerName www.sub.domain.tld

    ServerAlias *.sub.domain.tld

    ...

    </VirtualHost>

   

Any request to an address other than 111.22.33.55 will be served from the main server. A request to 111.22.33.55

with an unknown or no Host: header will be served from www.otherdomain.tld.

Mixed name-/IP-based vhosts

·         Setup: The server machine has three IP addresses (111.22.33.44, 111.22.33.55 and 111.22.33.66) which resolve to the names server.domain.tld, www.otherdomain1.tld and www.otherdomain2.tld respectively. The address 111.22.33.44

should we used for a couple of name-based vhosts and the other addresses for IP-based vhosts.

Server configuration:

    ...

    Port 80

    ServerName server.domain.tld

    NameVirtualHost 111.22.33.44

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/domain

    ServerName www.domain.tld

    ...

    </VirtualHost>

  

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/subdomain1

    ServerName www.sub1.domain.tld

    ...

    </VirtualHost>

   

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/subdomain2

    ServerName www.sub2.domain.tld

    ...

    </VirtualHost>

 

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/otherdomain1

    ServerName www.otherdomain1.tld

    ...

    </VirtualHost>

   

    <VirtualHost 111.22.33.66>



    DocumentRoot /www/otherdomain2

    ServerName www.otherdomain2.tld

    ...

    </VirtualHost>    

   

Port-based vhosts

·         Setup: The server machine has one IP address (111.22.33.44) which resolves to the name www.domain.tld. If we don't have the option to get another address or alias for our server we can use port-based vhosts if we need a virtual host with a different configuration.

Server configuration:

    ...

    Listen 80

    Listen 8080

    ServerName www.domain.tld

    DocumentRoot /www/domain

    <VirtualHost 111.22.33.44:8080>

    DocumentRoot /www/domain2

    ...

    </VirtualHost>

   

A request to www.domain.tld

on port 80 is served from the main server and a request to port 8080 is served from the virtual host.

Using _default_ vhosts

·         Setup 1: Catching every request to any unspecified IP address and port, i.e., an address/port combination that is not used for any other virtual host.

Server configuration:

    ...

    <VirtualHost _default_:*>

    DocumentRoot /www/default

    ...

    </VirtualHost>

   

Using such a default vhost with a wildcard port effectively prevents any request going to the main server.

A default vhost never serves a request that was sent to an address/port that is used for name-based vhosts. If the request contained an unknown or no Host: header it is always served from the primary name-based vhost (the vhost for that address/port appearing first in the configuration file).

You can use AliasMatch or RewriteRule to rewrite any request to a single information page (or script).

·         Setup 2: Same as setup 1, but the server listens on several ports and we want to use a second _default_ vhost for port 80.

Server configuration:

    ...

    <VirtualHost _default_:80>

    DocumentRoot /www/default80

    ...

    </VirtualHost>



   

    <VirtualHost _default_:*>

    DocumentRoot /www/default

    ...

    </VirtualHost>   

   

The default vhost for port 80 (which must appear before any default vhost with a wildcard port) catches all requests that were sent to an unspecified IP address. The main server is never used to serve a request.

·         Setup 3: We want to have a default vhost for port 80, but no other default vhosts.

Server configuration:

    ...

    <VirtualHost _default_:80>

    DocumentRoot /www/default

    ...

    </VirtualHost>

   

A request to an unspecified address on port 80 is served from the default vhost any other request to an unspecified address and port is served from the main server.

Migrating a name-based vhost to an IP-based vhost

·         Setup: The name-based vhost with the hostname www.otherdomain.tld

(from our name-based example, setup 2) should get its own IP address. To avoid problems with name servers or proxies who cached the old IP address for the name-based vhost we want to provide both variants during a migration phase.

The solution is easy, because we can simply add the new IP address (111.22.33.66) to the VirtualHost

directive.

Server configuration:

    ...

    Port 80

    ServerName www.domain.tld

    DocumentRoot /www/domain

    NameVirtualHost 111.22.33.55

    <VirtualHost 111.22.33.55 111.22.33.66>

    DocumentRoot /www/otherdomain

    ServerName www.otherdomain.tld

    ...

    </VirtualHost>

  

    <VirtualHost 111.22.33.55>

    DocumentRoot /www/subdomain

    ServerName www.sub.domain.tld

    ServerAlias *.sub.domain.tld

    ...

    </VirtualHost>

   

The vhost can now be accessed through the new address (as an IP-based vhost) and through the old address (as a name-based vhost).

Using the ServerPath

directive

·         Setup: We have a server with two name-based vhosts. In order to match the correct virtual host a client must send the correct Host:



header. Old HTTP/1. 0 clients do not send such a header and Apache has no clue what vhost the client tried to reach (and serves the request from the primary vhost). To provide as much backward compatibility as possible we create a primary vhost which returns a single page containing links with an URL prefix to the name-based virtual hosts.

Server configuration:

    ...

    NameVirtualHost 111.22.33.44

    <VirtualHost 111.22.33.44>

    # primary vhost

    DocumentRoot /www/subdomain

    RewriteEngine On

    RewriteRule ^/.* /www/subdomain/index.html

    ...

    </VirtualHost>

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/subdomain/sub1

    ServerName www.sub1.domain.tld

    ServerPath /sub1/

    RewriteEngine On

    RewriteRule ^(/sub1/.*) /www/subdomain$1

    ...

    </VirtualHost>

    <VirtualHost 111.22.33.44>

    DocumentRoot /www/subdomain/sub2

    ServerName www.sub2.domain.tld

    ServerPath /sub2/

    RewriteEngine On

    RewriteRule ^(/sub2/.*) /www/subdomain$1

    ...

    </VirtualHost>

   

Due to the ServerPath directive a request to the URL http://www.sub1.domain.tld/sub1/

is always

served from the sub1-vhost.

A request to the URL http://www.sub1.domain.tld/

is only served from the sub1-vhost if the client sent a correct Host: header. If no Host:

header is sent the client gets the information page from the primary host.

Please note that there is one oddity: A request to http://www.sub2.domain.tld/sub1/

is also served from the sub1-vhost if the client sent no Host:

header.

The RewriteRule

directives are used to make sure that a client which sent a correct Host: header can use both URL variants, i.e., with or without URL prefix.


Содержание раздела