Home > アーカイブ > 2011-05

2011-05

PHPの基本、phpinfo()の見方

  • 2011-05-30 (月)
  • PHP
この記事の所要時間: 921

PHPerにはお馴染みの関数、phpinfo()の見方です。

phpinfo()

PHPには多数の設定項目があり、それらを一覧する機能としてphpinfo()があります。

設定項目の他にインストールされている拡張機能や実行環境の情報が確認できるので、おそらく多くのPHPerが活用していると思います。

これからPHPを学ぶ人ならおさえておきたいphpinfo()の見方をまとめてみました。

1. phpinfo()の実行

まずは基礎の基礎、phpinfo()の実行です。

phpinfo()自体はただの関数ですので、PHPソースに記載するだけで良いです。

以下のソースをinfo.phpというファイルで保存します。

<?php
phpinfo();

ブラウザでこのファイルにアクセスすればphpinfoが表示されます。

1-1. ファイル名は?

Webでのサンプルなどを見るとphpinfo.phpというファイル名にしていることが多いようですが、ファイル名は何でも良いです。

1-2. 他のスクリプトを書いても良い

phpinfo()関数ではこの関数が実行されたタイミングで情報を出力するので、その前後で他の処理を書いても問題ありません。

例えば、以下のソースではphpinfo()の前後で現在時刻を出力しています。

<?php
// 何か処理
echo date('Y/m/d H:i:s').'<br />';

phpinfo();

// 何か処理
echo date('Y/m/d H:i:s').'<br />';

1-3. アクセスできる IP を制限する

phpinfoの情報は広く公開すべき内容ではないので、もし公開サーバで設置するならアクセス制限をかけた方が良いでしょう。

以下のソースでは、接続元IPアドレスが「xxx.xxx.xxx.xxx」以外ではphpinfoを表示しないようにしています。

<?php if ($_SERVER['REMOTE_ADDR'] !== 'xxx.xxx.xxx.xxx') die(); ?>
<?php phpinfo(); ?>

常にphpinfo()を表示する必要は無いでしょうから、内容を確認したら削除しておきましょう。

1-4. 表示セクションを変更する

phpinfo()を引数無しで実行すると全てのセクションが表示されますが、引数を指定することで、表示セクションを指定することができます。

引数にはセクション毎にINFO_*という定数が用意されていますので、こちらを指定します。なお定数値は各ビットの値となっているのでビット演算子で連結して複数のセクションを表示することができます。

<?php
phpinfo(INFO_CONFIGURATION); // 現在のディレクティブ(設定)情報を表示
<?php
phpinfo(INFO_ENVIRONMENT | INFO_VARIABLES); // $_ENVで取得できる環境変数とEGPCSで設定されている値を表示

指定できる定数についてはPHPマニュアルを参考にして下さい。
=> PHP: phpinfo – Manual

2. phpinfoの見方

phpinfoには数多くの情報があります。実際の良く確認する内容から各セクションの見方を見ていきましょう。

2-1. PHPが動作しているかと確認する

phpinfo()

まずはPHP自体が動いているかをphpinfo()で確認します。おそらく多くの方がPHPをインストールした際にはとりあえずphpinfo()を実行するでしょう。

phpinfoが表示されれば、PHP自体は動作していることが確認できます。

2-2. コンパイルオプションを確認する [Configure Command]

phpinfo()
Uploaded with Skitch!

PHPには多くのコンパイルオプションがあり、指定によって様々な機能を有効無効にすることができます。

現在動作しているPHPではどの機能が有効になっているかと確認します。

上記はyum(RPM)でインストールしたPHP 5.3.6のコンパイルオプションですが、様々な指定がされています。

2-3. php.iniファイルの位置を確認する[Loaded Configuration File等]

phpinfo()
Uploaded with Skitch!

「Loaded Configuration File」でPHPの設定ファイルであるphp.iniのパスを確認します。

RPMでインストールしたり、ソースからインストールしたりと何度もインストールを繰り返しているような場合、どのphp.iniを読み込んでPHPが実行されているかが分からなくなる時があります。(php.iniを変更したのに設定が反映されず、結局他のphp.iniが有効になっていたり。)

そういった際に現在有効となっているphp.iniファイルを確認します。

またRPMなどパッケージでインストールされたPHPでは拡張機能毎に設定ファイルが分けられているケースがあるので、「Additional .ini files parsed 」でphp.ini以外で読み込んでいる設定ファイルを核にします。

2-4. 設定ディレクティブの値を確認する[Local Value][Master Value]

phpinfo()
Uploaded with Skitch!

Configureセクションには現在設定されている各設定ディレクティブの値が表示されます。

1行につき1ディレクティブとなっており、「Local Value」と「Master Value」の2種類が表示されます。

これらの違いはマニュアルで明記されているわけではないのですが、「Master Value」が、php.ini(PHP-FPMなら/etc/php-fpm.d/www.conf)の設定値、「Local Value」が、httpd.confや .htaccess、ini_set()で設定した設定値となっているようです。phpinfo()を実行した環境では「Local Value」の値が有効となっています。

(httpd.conf は、Local Value に表示されていました。@DQNEOさん、ご指摘ありがとうございました。)

「Local Value」と「Master Value」を見て、想定どおりの設定値となっているか、なっていない場合はLocal Valueで書き換えられていないかなどを確認します。

2-5. 拡張機能がインストールされているかを確認する

phpinfo()
Uploaded with Skitch!

PHPには多くの拡張機能があるので、どの拡張機能がインストールされているかを確認します。

拡張機能が有効になっているとConfigureセクション内に専用のセクションが表示されます。専用セクションでは拡張機能のバージョン、設定情報、設定ディレクティブも表示されます。

例えば上記であれば、apcが有効になっていて、各設定情報が確認できます。

よくあるパターンとしては、yumでphpをインストールするとmbstringやpgsqlが有効になっていないので、それらがインストールされているかと確認したりします。

2-6. 環境変数を確認する

phpinfo()
Uploaded with Skitch!

phpinfo()を表示している環境で定義されている環境変数を確認します。

通常あまり意識しないかもしれませんが、例えばhttpd.confで環境変数を定義して、その値によりPHPアプリケーションの挙動を変えたい時などに環境変数の値を確認したりします。

2-7. EGPCS変数を確認する

phpinfo()
Uploaded with Skitch!

EGPCS($_ENV、$_GET、$_POST、$_COOKIE、$_SERVER)の値を確認します。

$_SERVERでHTTPリクエスト関連の値を見たり、$_COOKIEでセットされているcookieを確認したりします。

2-6 / 2-7 については、phpinfo()ではなく、PHPスクリプトでvar_dump()したりすることが多いですが、設定されている値が全て確認できるのは便利ですね。

おまけ. ブラウザの検索を使う

知りたい内容がはっきりしているなら、できるだけブラウザの検索機能(多くは[ctrl]+[f])で、目的のキーワードを入力して検索しましょう。

目で上から順に追っていって探すこともできますが、見落としたり、あれ、どこだっけ?とあちこち見て回るのも無駄なので、知りたい内容がはっきりしているならさっさと検索した方が早いです。

もちろん全部を眺めてみたいという目的であれば、じっくり見るものアリです。

3. コマンドラインでphpinfo

ここまではブラウザでphpinfoを見る方法を紹介してきましたが、コマンドライン(CLI)環境でもphpinfoを表示することができます。

方法は、phpコマンドに「-i」オプションを付けて実行するだけです。出力はテキスト形式となります。

$ php -i
phpinfo()
PHP Version => 5.3.6

System => Linux xxx.xxxx.xxxxx 2.6.18-194.26.1.el5 #1 SMP Tue Nov 9 12:54:20 EST 2010 x86_64
Build Date => Apr 15 2011 18:10:43
.....

個人的にはブラウザ上よりCLIでphpinfoを確認することが多いです。良く使う方法としては以下です。

3-1. phpinfoをファイルに保存

$ php -i > info

3-2. php.iniファイルを探す

$ php -i | grep ini

iniファイルを見るには「php –ini」という方法もあるようです。(@murstsさん、ありがとうございました。)

$ php --ini

3-3. include_pathを確認する

$ php -i | grep include_path

3-4. apcがインストールされているか確認する

$ php -i | grep apc

phpinfo()でPHPの状態を知る

phpinfo()には多くの情報があるので、PHPがどのようにインストールされているか、どの機能が有効になっているか、設定ディレクティブにどの値が設定されているかを一元的に把握することができます。

PHPを活用していくなら避けて通れない内容ですので上手くphpinfo()を活用して下さい。

まずは手元の環境でどのような設定をされているかを確認してみてはいかがでしょうか。

PHPでsleep sort

  • 2011-05-20 (金)
  • PHP
この記事の所要時間: 027

コロンブスの卵的なソートアルゴリズム「sleep sort」をPHPで実装してみました。

via . 常識を覆すソートアルゴリズム!その名も”sleep sort”! – Islands in the byte stream

fork使うので、pcntlを有効にします。

sudo port install php5-pcntl

さくっと実装。

実行

% php sleepsort.php
% 12345678910 

nginx+php-fpmをyumでインストールして、WordPress/CakePHPを動かす設定

この記事の所要時間: 4242

www.1×1.jpの環境をApache+mod_phpな環境から、nginx+php-fpmな環境へ移行しました。

さくらVPSのCentOS5.5環境にnginx+php-fpmをyumでインストールして、CakePHPとWordPressを動かす設定を行いました。

このエントリでは導入ということで、インストールから、とりあえず動作するところまでをご紹介します。

0. 構成

nginx+php-fpm環境にCakePHPとWordPressをインストールします。

それぞれ以下のURLでアクセスできるようにします。

http://www.1×1.jp/ -> CakePHP

http://www.1×1.jp/blog/ -> WordPress

1. インストール

nginxとphp-fpmだとソースからインストールするパターンが多いですが、ここではyumでインストールします。

1-1. remiリポジトリを登録

centosリポジトリにはnginx、php-fpmが含まれていないので、epel / remiリポジトリを登録します。

$ sudo wget http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpm
$ sudo wget http://rpms.famillecollet.com/enterprise/remi-release-5.rpm
$ sudo rpm -Uvh remi-release-5*.rpm epel-release-5*.rpm

1-2. yumでインストール

nginxとphp-fpmをyumでインストールします。–enablerepo=remi で1-1で登録したremiリポジトリを指定することを忘れないようにしましょう。

他にphp-mbstringやphp-cliなんかもいれてますが、このあたりはお好みで。

$ sudo yum -y install nginx php-cli php-fpm php-mbstring --enablerepo=remi

2011/05/16現在インストールされるバージョンは以下です。

$ /usr/sbin/nginx -V
nginx version: nginx/0.8.54
built by gcc 4.1.2 20080704 (Red Hat 4.1.2-50)
TLS SNI support disabled
configure arguments: --user=nginx --group=nginx --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/subsys/nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_perl_module --with-mail --with-file-aio --with-mail_ssl_module --with-ipv6 --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic'
$ /usr/sbin/php-fpm -v
PHP 5.3.6 (fpm-fcgi) (built: Apr 15 2011 18:13:37)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies

2. nginxの設定

nginxの設定を行います。yumでインストールすると設定ファイルは /etc/nginx 以下に配置されます。/etc/nginx/nginx.confがメインの設定ファイルになっているのでこれを編集します。

Apacheの設定を知っていれば何となく理解できるかと思いますが、リクエストURIがlocationディレクティブにマッチすれば該当ブロックの設定が適用されます。

2-1. バージョン情報の出力をoff

HTTPレスポンスヘッダやエラーページでnginxのバージョン情報を出力しないようにします。

server_tokens     off; 

2-2. gzipをon

gzipをonにします。

    gzip  on;

2-3. /blogをWordPressに

/blogというURLに対してWordPress用の設定を行っています。

内容はなんとなく分かるかと思いますが、前半のブロックでApacheでいうmod_rewriteのような設定を行っています。これにより存在しないディレクトリ、ファイルへのアクセスがあった場合は/blog/index.php?q=PATHへURLをリライトします。

後半のブロックがphp-fpm(FastCGI)の設定です。^/blog/.+\.php$にマッチするリクエストであれば、php-fpmへリクエストを送信します。

        # wordpress
        location /blog {
            alias   /path/to/wordpress;
            index  index.php;

            if (!-e $request_filename) {
                rewrite ^/blog(.+)$  /blog/index.php?q=$1 last;
                break;
            }
        }
        location ~ ^/blog/.+\.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info ^/blog(.+\.php)(.*)$;
            fastcgi_param  SCRIPT_FILENAME  /path/to/wordpress$fastcgi_script_name;
            fastcgi_intercept_errors on;
            include        fastcgi_params;
        }

2-4. /blog以外のURLはCakePHPに

/blog以外のURLに対してCakePHP用の設定を行っています。

2-3と同じく、前半のブロックでURLリライトの設定を行っています。存在しないディレクトリ、ファイルへのアクセスがあった場合は/index.php?url=PATHへURLをリライトします。

後半のブロックでは、\.php$にマッチするリクエストであれば、php-fpmへリクエストを送信します。

        # cakephp
        location / {
            root   /path/to/cakephp/app/webroot;
            index  index.php index.html index.htm;

            if (!-e $request_filename) {
                rewrite ^(.+)$  /index.php?url=$1 last;
                break;
            }
        }
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /path/to/cakephp/app/webroot$fastcgi_script_name;
            fastcgi_intercept_errors on;
            include        fastcgi_params;
        }

2-5. .htaccess / .git / .svnはアクセス禁止に

.htaccess / .git / .svnはアクセスできないようにしています。

        location ~ (\.ht|\.git|\.svn) {
            deny  all;
        }

2-6. /etc/nginx/nginx.conf

変更した /etc/nginx/nginx.conf は以下です。

#######################################################################
#
# This is the main Nginx configuration file.  
#
# More information about the configuration options is available on 
#   * the English wiki - http://wiki.nginx.org/Main
#   * the Russian documentation - http://sysoev.ru/nginx/
#
#######################################################################

#----------------------------------------------------------------------
# Main Module - directives that cover basic functionality
#
#   http://wiki.nginx.org/NginxHttpMainModule
#
#----------------------------------------------------------------------

user              nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;


#----------------------------------------------------------------------
# Events Module 
#
#   http://wiki.nginx.org/NginxHttpEventsModule
#
#----------------------------------------------------------------------

events {
    worker_connections  1024;
}


#----------------------------------------------------------------------
# HTTP Core Module
#
#   http://wiki.nginx.org/NginxHttpCoreModule 
#
#----------------------------------------------------------------------

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    server_tokens     off;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;
    
    server {
        listen       80;
        server_name  _;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # wordpress
        location /blog {
            alias   /path/to/wordpress;
            index  index.php;

            if (!-e $request_filename) {
                rewrite ^/blog(.+)$  /blog/index.php?q=$1 last;
                break;
            }
        }
        location ~ ^/blog/.+\.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_split_path_info ^/blog(.+\.php)(.*)$;
            fastcgi_param  SCRIPT_FILENAME  /path/to/wordpress$fastcgi_script_name;
            fastcgi_intercept_errors on;
            include        fastcgi_params;
        }

        # cakephp
        location / {
            root   /path/to/cakephp/app/webroot;
            index  index.php index.html index.htm;

            if (!-e $request_filename) {
                rewrite ^(.+)$  /index.php?url=$1 last;
                break;
            }
        }
        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /path/to/cakephp/app/webroot$fastcgi_script_name;
            fastcgi_intercept_errors on;
            include        fastcgi_params;
        }

        location ~ (\.ht|\.git|\.svn) {
            deny  all;
        }
    }

    # Load config files from the /etc/nginx/conf.d directory
    include /etc/nginx/conf.d/*.conf;
}

3. php-fpmの設定

次にphp-fpmを設定します。 yumでインストールすると設定ファイルが/etc/php-fpm.confと/etc/php-fpm.d/www.confに配置されます。

php-fpm.confはとりあえずデフォルトのままで、www.confを編集します。変更するのは4箇所です。

3-1. 実行ユーザ

php-fpmの実行ユーザをnginxと同一にしておきます。

user = nginx

3-2. 実行グループ

実行ユーザと同じく実行グループもnginxと同一にしておきます。

group = nginx

3-3. プロセス生成方法

php-fpmの実行プロセス生成方法を指定します。動的にプロセス数を増減するならdynamicを、設定したプロセス数に固定するならstaticを指定します。

ここでは利用するリソースが把握しやすいstaticにします。

pm = static

3-4. 生成するプロセス数

生成するphp-fpmプロセス数を指定します。ここでは10プロセスを生成します。

他にpm.start_servers / pm.min_spare_servers/ pm.max_spare_serversといったプロセス数に関する設定がありますが、pm=staticの場合は影響ありません。

pm.max_children = 10

3-5. expose_phpをoffに

HTTPレスポンスヘッダに含まれるPHPバージョン情報を出力しないようにexpose_phpをoffにしています。

このようにPHP関連の設定はwww.confで記述することもできます。(もちろんphp.iniで設定しても良いです。)

php_admin_flag[expose_php] = off

3-6. /etc/nginx/nginx.conf

; Start a new pool named 'www'.
[www]

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

; Set listen(2) backlog. A value of '-1' means unlimited.
; Default Value: -1
;listen.backlog = -1

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
listen.allowed_clients = 127.0.0.1

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
;                 mode is set to 0666
;listen.owner = nobody
;listen.group = nobody
;listen.mode = 0666

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache Choosed to be able to access some dir as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives:
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
; Note: This value is mandatory.
pm = static

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes to be created when pm is set to 'dynamic'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI.
; Note: Used when pm is set to either 'static' or 'dynamic'
; Note: This value is mandatory.
pm.max_children = 10

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 5

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 5

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 35

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. By default, the status page shows the following
; information:
;   accepted conn    - the number of request accepted by the pool;
;   pool             - the name of the pool;
;   process manager  - static or dynamic;
;   idle processes   - the number of idle processes;
;   active processes - the number of active processes;
;   total processes  - the number of idle + active processes.
; The values of 'idle processes', 'active processes' and 'total processes' are
; updated each second. The value of 'accepted conn' is updated in real time.
; Example output:
;   accepted conn:   12073
;   pool:             www
;   process manager:  static
;   idle processes:   35
;   active processes: 65
;   total processes:  100
; By default the status page output is formatted as text/plain. Passing either
; 'html' or 'json' as a query string will return the corresponding output
; syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;pm.status_path = /status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
;ping.path = /ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
;ping.response = pong

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = /var/log/php-fpm/www-slow.log

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: chrooting is a great security feature and should be used whenever
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot =

; Chdir to this directory at the start. This value must be an absolute path.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Default Value: no
;catch_workers_output = yes

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'.
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Default Value: nothing is defined by default except the values in php.ini and
;                specified at startup with the -d argument
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
;php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_flag[expose_php] = off
;php_admin_value[memory_limit] = 32M

4. nginx / php-fpmの起動

nginxとphp-fpmを起動します。

$ sudo /etc/init.d/nginx start
$ sudo /etc/init.d/php-fpm start

起動に成功すれば、0.0.0.0:80と127.0.0.1:9000がLISTENになっているはずです。

$ netstat -ltn | grep -E '(80|9000)'
tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN   

サーバ起動時に自動実行されるようにchkconfigで登録しておきます。

$ sudo /sbin/chkconfig nginx on
$ sudo /sbin/chkconfig php-fpm on

あとはCakePHP / WordPressをインストールすればokです。

5. 実際に使ってみて

Apache+mod_phpからの移行ということで基本Apache感覚で触りだしたわけですが、つまづいたというか気になったことを。

5-1. Aliasはaliasで

ApacheのAliasのようなことをやりたい場合、locationディレクティブでURIを指定して、そのブロック内ではrootではなく、aliasにてディレクトリを指定します。

        location /blog {
            alias   /path/to/wordpress;
            index  index.php;
        }

5-2. .htaccessは使えない

CakePHPでもWordPressでも使われている.htaccessですが、nginxでは利用できません(反映されません)。

nginxには.htaccessのようにサーバが設定ファイルを再読込することなく設定を動的に変更する方法はありません。

.htaccessで指定するような、アクセス制御、mod_rewrite、Basic認証等はnginx.confなどの設定ファイルにて記述し、nginxを再起動(再読込)を実行して設定ファイルを反映します。

# nginx 再起動
$ sudo /etc/init.d/nginx restart

# nginx 設定ファイル再読込
$ sudo /etc/init.d/nginx reload

5-3. Digest認証がない

nginxにはDigest認証を実現するモジュールは無いようです。以前はDigest認証を利用している箇所があったのですが、Basic認証は利用できるのでHTTPS+Basic認証で代用しました。

5-4. PHP関連の設定を変更したら

php.iniやwww.confでPHP関連の設定を変更した場合、php-fpmを再起動(再読込)します。nginxを再起動したところでphp-fpmには反映されませんのでご注意を。

# php-fpm 再起動
$ sudo /etc/init.d/php-fpm restart

# php-fpm 設定ファイル再読込
$ sudo /etc/init.d/php-fpm reload

5-5. rewrite対象URLにアクセスして画面が真っ白に

ここで設定した内容では、http://example.com/foo/bar といったファイルが存在しないURLへアクセスすると /index.php?url=URLというURLへrewriteして処理を行います。

こういった状況で画面が真っ白になるという現象がありました。

結局、原因はnginx.confの設定で、rewriteしたPHPスクリプトがSCRIPT_FILENAME で指定したパスに存在しない(アクセスできない)とこういった現象になるようです。

nginx、php-fpm どちらのログにも何も出力されなかったのではじめは嵌りました。もし同じ現象になった際はnginx.confのSCRIPT_FILENAMEの設定を確認してみて下さい。

nginxをはじめるのにオススメの本

これからnginxをはじめるなら「ハイパフォーマンスHTTPサーバ Nginx入門」がおすすめです。

現時点(2011/05/19)で日本語で書かれたnginx解説本がこれしか無いということもありますが、nginxをこれから利用するにとっては分かりやすく解説されています。

ただ、いきなりシェルコマンドやLinuxファイルシステム、システム管理ツールの解説が60ページほど続くので、この部分だけを立ち読みして「こりゃダメだ」と判断しないように注意して下さい:D このあと30ページほどnginxをインストールする内容があって、ようやく本編がはじまります。その後はしっかりとnginxについて解説されていますのでご安心を。

各ディレクティブの設定については公式WikiをはじめWebに情報があるのですが、設定の基本的な思想や細かなTipsなどは書籍にまとまっていると理解しやすいですね。php-fpmとの連携やApacheとの連携(リバースプロキシ)、Apacheからの移行なども簡単に解説されているので、Apahce+mod_phpから移行しようかなという方は一度手にとってみてください。

開発合宿関西3に参加してきました

この記事の所要時間: 344

滋賀で開催された開発合宿関西3に2泊3日で参加してきました。

場所は昨年もお世話になった琵琶湖湖畔にある「アクティプラザ琵琶」です。

ここは、無線LAN完備で、電源ももちろんあって、開発の大部屋があって、ゆっくり寝る部屋もあって、ご飯も美味しくて、空気も美味してくて、大きなお風呂があってと合宿するにはもってこいの環境です。

なんといっても周辺徒歩圏内には何にも娯楽施設(コンビニ含む)が無いので、がっつり開発に集中できるのが良いですね。昨年もこの環境のおかげで集中して作業できたので、味をしめてまた参加しました。

今回は、何かをじっくり作るというより、日頃やろうとしつつも手を付けられなかった事をあれこれやってきました。

1. www.1×1.jp のサーバ移行

先日のサーバ障害で一旦AWSへ移行していたwww.1×1.jpサイトをさくらVPSへ移行しました。

その際にこれまでApache+mod_phpだった環境をnginx+php-fpm構成へ変更しました。前々からこの構成には興味があったので、試せて良かったです。

これまでnginxはリバースプロキシや静的ファイル配信では利用していたのですが、factcgi連携は初だったのでハマりつつも初日に移行することができました。

nginx+php-fpm構成で、WordPressとCakePHPを動かすことができたので、詳細は別エントリに書きたいと思います。

ちなみに、このblogもnginxで動作しています。

2. follow-ok.in / iscot.in などのWebサービスのサーバ移行

その他サービスについては、nginxをリバースプロキシにしたLAPP環境へ移行しました。

移行自体はすんなり終わったのですが、さくらVPSのPort25が開いてないのでDNSの変更はしていません。ポートが解放されたら、DNSを変更する予定です。

1.と2.で別構成にすることで、nginxとPHPを使うならどちらが向いているのかを今後見ていくつもりです。

3. Behat / Selenium / Jenkins

やってみたかったことでテスト関連、特に Behat / Selenium / Jenkins を触ってみました。

Behatは、他の方のエントリを読むと準備が大変そうなイメージがありましたが、試してみるとxUnitを書く感覚でテンポ良く、テストが書けそうな印象を持ちました。

Seleniumは、Firefox4にIDEを入れるのにつまづいたりしましたが、PHPUnitのPHPUnit_Extensions_SeleniumTestCaseでテストケースを読み込んで実行できることが分かるなど発見がありました。(CakePHPがSimpleTestを採用していることもあって、PHPUnit自体をしばらく追っかけてなかったのですが、アノテーションで動作を指定できるとか全然知りませんでした。。。)

Jenkinsは、インストールまでは前もってやっていたので、実際のPHPプロジェクトで利用するパターンを試していました。とりあえずSeleniumで作ったテストケースについては、PHPUnitを使えば簡単に連携できたので、これは業務のプロジェクトでも利用してみます。

テスト関連は自分の中でも再燃しているところなので、もう少し追っかけていきます。

4. Kansai PHP Users Group 発足準備

Kansai PHP Users Groupという会を立ち上げようと思っていて、その準備をやっていました。

やっぱりみんなで話すとサクサク決まって良いですね。

詳細はまた後日:D

成果を出すイベント

このイベントは運営側から課題が出るわけではなく、参加者が自分で決めた課題を黙々とこなすイベントです。

集中して作業したり、ざっくばらんに雑談(技術話ももちろん込み)をしたり、のバランスが自然に上手く取れているのが良いなあ感じました。

参加したからには何らかの成果を出して帰りたいので、朝から晩(夜中)までみんなで頑張っていました。

意識の高い人達からの良い刺激を受けつつ、自分のタスクを集中してこなす。バタバタしている今となってはとても贅沢な時間を過ごせました。やっぱりこういう時間を取って自分なりに咀嚼していかないと枯渇する一方ですね。また行きたいなー。

Firefox4 に Selenium IDE をインストールする

この記事の所要時間: 18

滋賀に開発合宿に来てます。

Firefox4にSelenium IDEをインストールしようとしてハマったのでメモ。

  1. Firefox4にAdd-on Compatibility Reporterをインストール
  2. Selenium DownloadsからSelenium IDE(http://release.seleniumhq.org/selenium-ide/1.0.10/selenium-ide-1.0.10.xpi)[2011/05/07時点]をダウンロード
  3. ダウンロードしたxpiファイルをFirefox4のウィンドウにドラッグ
  4. いつものインストール確認画面が表示されるので、確認してインストール。

この手順では、Add-on Compatibility ReporterでFirefoxのバージョンチェックを無効にして、Selenium IDEをインストールしています。試した限りでは、問題無く動きました。

いずれSelenium IDE自体がFirefox4に正式対応して普通にインストールできるようになると思うんですが、他のプラグインでも同じことがありそうなので覚えておくと良いですね。(ただバージョンチェックを無効にするので利用はご自身の責任でお願いします。)

@nntsugu さんありがとうございますー。

Home > アーカイブ > 2011-05

検索
フィード
メタ情報

Return to page top