- 2010年5月17日 21:00
PHPスクリプトで表示されるホームページではリクエストごとに処理がされます。
その処理の必要性がなければ304コードを返すようにするという方法を紹介。
304コードはブラウザのキャッシュから表示されるようになるものです。
流れを説明すると以下の通りです。
新規リクエストには通常処理をして返答。
次回以降のリクエストではページが更新されていなければ304コードを返答。
これにより不要な処理が発生せず、サーバーの負荷対策にも繋がるものです。
詳しくは参照URLをご覧いただければいいとして、ここでは私個人の為のメモとして書き残しておきたいと思います。
<?php $ts = getlastmod(); doConditionalGet($ts); function doConditionalGet($timestamp) { // A PHP implementation of conditional get, see // http://fishbowl.pastiche.org/archives/001132.html $last_modified = gmdate('D, d M Y H:i:s T', $timestamp); $etag = '"'.md5($last_modified).'"'; // Send the headers header("Last-Modified: $last_modified"); header("ETag: $etag"); // See if the client has provided the required headers $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : false; $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : false; if (!$if_modified_since && !$if_none_match) { return; } // At least one of the headers is there - check them if ($if_none_match && $if_none_match != $etag) { return; // etag is there but doesn't match } if ($if_modified_since && $if_modified_since != $last_modified) { return; // if-modified-since is there but doesn't match } // Nothing has changed since their last request - serve a 304 and exit header('HTTP/1.1 304 Not Modified'); exit; } ?>
複数のファイルから更新日を取得して処理する場合
<?php$ts = getlastmod();$ts_list[] = getlastmod(); $ts_list[] = filemtime('<$MTBlogSitePath$>left-column.php'); $ts_list[] = filemtime('<$MTBlogSitePath$>right-column.php'); sort($ts_list, SORT_NUMERIC); $ts = array_pop($ts_list); doConditionalGet($ts);
私は、この手法をPHP化したMTへ組み込んで負荷対策を施しました。
尚、流石にコードの量があるのでコードを外部ファイルからインクルードで読み込むようにしました。
- Newer: サイトマップ 検索エンジン(Google, Yahoo, Bing[MSN])対策
- Older: MT PHP化
Comments:0
Trackbacks:0
- TrackBack URL for this entry
- https://www.fya.jp/cgi-bin/mt/mt-tb.cgi/95
- Listed below are links to weblogs that reference
- PHP 304 Not Modified from Minase's Blog - FYA