misc.log

日常茶飯事とお仕事と

PHPの開発環境を揃えてみる(2) Apache導入

先日の「PHPの開発環境を整えてみる(http://www.backyrd.net/entry/20140508/1399561090)」の続きです。

VMware上で動くWindows7に、Eclipse KeplerとPDT(PHP Development Tools)を導入するとこまでは終了。一旦その状態のスナップショット*1を取っておきました。次は、Webサーバーの導入と設定を行います。

Apacheをダウンロードする

本当であればサーバーOS(Windows Serverなど)を別途用意した方がいいのですが、流石に仮想PCを2台動かすのは少々負荷になるので、まずは開発用のWindows7にHTTPサーバー「Apache」を導入します。

Apacheは下記のリンクにある「Download!」のところからダウンロードして利用します。

Apache / HTTP Server Project
http://httpd.apache.org/

バージョンは最新版である「2.4.9」を利用してみようかとおもったのですが、32bit Windows版の安定版はApache 2.2とのこと。少なくともダウンロードサイトにお手軽インストールが可能なmsi形式のリンクが無かったので、ダウンロードサイトから「binaried」→「Win32」→「httpd-2.2.25-win32-x86-no_ssl.msi 」を選択してダウンロードします。別にSSL対応バージョンもあるようですが、SSLは使わないので「no_ssl」のほうにしました。

Apacheをインストールする

Apacheインストーラーはmsi形式なので、そのままダブルクリックするとインストールが開始されます。途中、ドメイン名とサーバー名を聞かれるので、とりあえず「localhost」と入力。ポート番号80で待ち受けるWindows Serviceとしての起動を選択して先に進めます。

最終的に、Apache本体は「C:\Program Files\Apache Software Foundation\Apache2.2\」にインストールされるようです。

f:id:frontline:20140511145734j:plain

インストール後、既にWindows ServiceとしてApache 2.2が起動していることが確認できました。

f:id:frontline:20140511145954j:plain

続いて、実際のWebサイトのアクセス確認。「http://localhost/」でブラウザからアクセスすると……

f:id:frontline:20140511150210j:plain

オーケー!イット、ワークス!とのことですので、動いてますね。とりあえずWebサーバーのセットアップ完了です。

Webページ用HTMLファイルの所在を変更する

Apache導入直後の状態では、Webサーバーとして公開するフォルダとそこにあるHTMLファイルは以下のフォルダに用意されるようです。

C:\Program Files\Apache Software Foundation\Apache2.2\htdocs

実際にそのフォルダとHTMLファイルを見てみるとこんな感じです。

f:id:frontline:20140511150551j:plain

流石にProgram Files以下を外部に晒すというのは気持ち悪いので、設定ファイルを変更して公開フォルダを変更してみます。設定ファイルは「C:\Program Files\Apache Software Foundation\Apache2.2\conf」フォルダにあり、ファイル名は「httpd.conf」。このテキストファイルの中にある以下の記述を変更すれば、公開するフォルダを変更できます。

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"

このDocumentRoot設定に、公開するフォルダを記載します。ここでは以下のように書き換えてみます(記号「#」を行頭に書くと、その行はコメント行になります。万が一を考えて元の設定を残しておきたい場合は#をつけてコメントにしておきましょう)。

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
#DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"
DocumentRoot "C:/work/web"

さらに、公開用フォルダの設定を行っている箇所のパス指定を変更します。

#
# This should be changed to whatever you set DocumentRoot to.
#
#<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">
<Directory "C:/work/web">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

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

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all

</Directory>

なお、前述のようにProgram Files配下にApacheをインストールした場合、設定ファイルを変更する際にアクセス権がないというエラーが発生してしまいます(保存できない)。これを回避するには、インストール先をProgram Files以外に変更するか、ファイルのアクセス権を変更する必要があるので注意してください。

PHPを利用可能にする

Apache上のWebページでPHPを利用できるようにします。

PHP本体の導入

まず、PHPを解釈して処理するためのプログラムをWebサーバーにするPCにインストールします。最新版のWindowsPHPはVersion 5.5.12のようなので、こちらからダウンロードしようとしたのですが……どうやら5.5.12はApache 2.2には対応していないようなので、敢えて古いバージョン、「5.4.28」をダウンロードします。

PHP for Windows Download
http://windows.php.net/download/

ダウンロードリンクには「Thread Safe」と「Non Thread Safe」があります。これは以下のFAQによると「マルチスレッド処理するWebサーバーかどうか」で使い分けをすればよいようです。Apacheはマルチスレッド対応なので、Thread Safeバージョンをダウンロードします。

PHPを手に入れるには
http://www.php.net/manual/ja/faq.obtaining.php

ファイルをダウンロードしたら、WebサーバーにするPC上に専用のフォルダを作り、内容を展開します(Zipファイルです)。展開したら、「php.ini-development」をコピーしてファイル名を「php.ini」に変更します。これが基本の設定ファイル。

このあたりについては下記リンク先も参考にしてください。

Windowsシステムへのインストール/手動のインストール
http://www.php.net/manual/ja/install.windows.manual.php

次はApache専用の設定。詳細は下記のリンクにあります。

Windowsシステムへのインストール/Apache 2.x (Microsoft Windows 用)
http://www.php.net/manual/ja/install.windows.apache2.php
スクリプト実行方式の選択

ApachePHPによるスクリプトを実行するには方法が2通りあります。CGIによる方法は、実際のコンテンツの冒頭(HTMLファイルの冒頭)に、PHPを解釈するプログラム名を「#!C:/php/php.exe」のような記述で指定して処理させる方式です。もう1つはハンドラーとよばれる、拡張子などに応じて自動的に処理用プログラムを選択指定できる「定義」を記述、Apacheがそれに応じて適宜処理を切り分ける方式です。Visual BasicC#などでの「イベントハンドラー」も「こういうイベントがあったら、この関数を呼んでね」という定義をあらかじめ書いておく、というもので、同じ発想によるものです。

今回ですが、このハンドラー指定による方式を利用します(たぶんこっちの方が今は一般的のようなので)。これにはApacheの設定ファイル「httpd.conf」に以下の記述を追記する必要があります。

LoadModule php5_module "c:/work/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php

# php.ini へのパスを設定します
PHPIniDir "C:/work/php"

最後の「php.iniへのパス」は、各環境でphpのファイル一式を展開したフォルダを指定してください。

mod_rewriteの設定

次に、CodeIgniterで利用するURL表記法を実現するために必要なDLLを指定します。

Apacheの設定ファイル「httpd.conf」にある下記行のコメントを外します。

#LoadModule rewrite_module modules/mod_rewrite.so

これだけでは駄目で、URLの書き換えに関する設定が必要です。細かい設定も可能らしいのですが、記法を調べている時間が無いので手順にあるとおりに……とお持ったのですが、この設定は「.htaccess」ファイルか「httpd.conf」に書くそうです。ここでは、httpd.confに書くことにします。以下の記述をファイルの末尾にでも追記してください。

RewriteEngine on
RewriteCond $1 !^/(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

上記の設定は、「CodeIgniter ユーザガイド 日本語版 Version 2.0.3」の「index.php ファイルをURLから除去する」のところに記載されていた一番単純のな設定です。

CodeIgniter ユーザガイド 日本語版 Version 2.0.3
http://codeigniter.jp/user_guide_ja/general/urls.html
PHPの設定

次にphp.iniの設定変更です。とりあえずの設定ということで、以下php.iniの以下の部分を書き換え、追記しました。

; example, if you set output_handler to "mb_output_handler", character
; encoding will be transparently converted to the specified encoding.
; Setting any output handler automatically turns on output buffering.
; Note: People who wrote portable scripts should not depend on this ini
;   directive. Instead, explicitly set the output handler using ob_start().
;   Using this ini directive may cause problems unless you know what script
;   is doing.
; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler"
;   and you cannot use both "ob_gzhandler" and "zlib.output_compression".
; Note: output_handler must be empty if this is set 'On' !!!!
;   Instead you must use zlib.output_handler.
; http://php.net/output-handler
output_handler = mb_output_handler
; PHP's default character set is set to empty.
; http://php.net/default-charset
default_charset = "UTF-8"
; UNIX: "/path1:/path2"
;include_path = ".:/php/includes"
;
; Windows: "\path1;\path2"
include_path = ".;c:\work\php\includes"
; The root of the PHP pages, used only if nonempty.
; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root
; if you are running php as a CGI under any web server (other than IIS)
; see documentation for security issues.  The alternate is to use the
; cgi.force_redirect configuration below
; http://php.net/doc-root
doc_root ="c:\work\web"
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "C:\work\php\ext"
; Windows Extensions
; Note that ODBC support is built in, so no dll is needed for it.
; Note that many DLL files are located in the extensions/ (PHP 4) ext/ (PHP 5)
; extension folders as well as the separate PECL DLL download (PHP 5).
; Be sure to appropriately set the extension_dir directive.
;
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
extension=php_mbstring.dll
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = "Asia/Tokyo"
[mbstring]
; language for internal character representation.
; http://php.net/mbstring.language
mbstring.language = Japanese

; internal/script encoding.
; Some encoding cannot work as internal encoding.
; (e.g. SJIS, BIG5, ISO-2022-*)
; http://php.net/mbstring.internal-encoding
mbstring.internal_encoding = UTF-8

; http input encoding.
; http://php.net/mbstring.http-input
;mbstring.http_input = UTF-8
mbstring.http_input = auto

; http output encoding. mb_output_handler must be
; registered as output buffer to function
; http://php.net/mbstring.http-output
;mbstring.http_output = pass
mbstring.http_output = utf-8

; enable automatic encoding translation according to
; mbstring.internal_encoding setting. Input chars are
; converted to internal encoding by setting this to On.
; Note: Do _not_ use automatic encoding translation for
;       portable libs/applications.
; http://php.net/mbstring.encoding-translation
;mbstring.encoding_translation = Off
mbstring.encoding_translation = On

; automatic encoding detection order.
; auto means
; http://php.net/mbstring.detect-order
mbstring.detect_order = auto

; substitute_character used when character cannot be converted
; one from another
; http://php.net/mbstring.substitute-character
mbstring.substitute_character = none

; overload(replace) single byte functions by mbstring functions.
; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(),
; etc. Possible values are 0,1,2,4 or combination of them.
; For example, 7 for overload everything.
; 0: No overload
; 1: Overload mail() function
; 2: Overload str*() functions
; 4: Overload ereg*() functions
; http://php.net/mbstring.func-overload
mbstring.func_overload = 0

; enable strict encoding detection.
mbstring.strict_detection = On

設定変更後は、Apacheを再起動します。再起動はWindowsの管理ツールにある「サービス」から、Apache2.2を選択し、再起動を指定してください。

PHPの動作確認

では、実際にPHPの処理が動くことを確認します。先の「It works!」のHTMLファイルを以下のように書き換えて、ファイル名も「index.php」に拡張子を変えてしまいます。

<html><body><h1>It works!</h1>
<?php phpinfo(); ?>
</body></html>

これで、It works!のうしろにPHPの設定一覧が表示されるはずです。

f:id:frontline:20140511173054j:plain

上手くいきました。とりあえずは、これでPHPを動かせるWebサーバー環境の完成です。

Apacheハンドブック

Apacheハンドブック

*1:スナップショット: VMware Workstationが持つ機能の1つで、ある時点の仮想PCの状態そのものを保存するというものです。保存した状態は時系列にツリー上に表示、管理され、好きなときに「以前のあの時の状態」に戻すことができるという便利機能。スナップショットはお手軽な状態保存ですが、ほかにも完全に同じ仮想PCをコピー作成する「クローン」などもあります。この辺が仮想PCを開発者の立場で利用する最大のメリット。