hack のためのネタ帳, etc,,,

状況

DOCUMENT_ROOT の問題

承前で
$requestedAbsoluteFile = rtrim(dirname(__FILE__) . $exploded_REQUEST_URI[0], "/");
とかしてたら、
+ docroot1
| + index.phtml
| + router.php
+ docroot2
  + index.phtml
みたいな状態で docroot2 以下で
php -S localhost:8080 ../docroot1/router.php
みたいにした場合に docroot2/index.phtml が開けなかった(当たり前)。
dirname(FILE) ではなく $_SERVER["DOCUMENT_ROOT"] にする必要がある。

include がネストした場合の基準ディレクトリと相対パスの問題

の通りだが、include 元の pwd が基準になるので、include 先のファイルから相対パスで更に include すると include 出来ない。

.html や .htm が charset=UTF-8 扱いになる問題

return FALSE; で built-in web server に .html や .htm の処理を任せると、ini_set('default_charset', NULL); を指定しても問答無用で Content-Type に charset=UTF-8 を付与されてしまった。
readfile() を使って自前で処理する必要がある模様。

以上を踏まえた修正版

とりあえずこんな感じでお茶を濁した。

router.php

<?php
$indexFiles = ["index.phtml", "index.phtm"];
$exploded_REQUEST_URI = explode("?", $_SERVER["REQUEST_URI"]);
$requestedAbsoluteFile = rtrim($_SERVER["DOCUMENT_ROOT"] . $exploded_REQUEST_URI[0], "/");
if (is_dir($requestedAbsoluteFile)) {
  foreach ($indexFiles as $filename) {
    $fn = $requestedAbsoluteFile.'/'.$filename;
    if (is_file($fn)) {
      $exploded_REQUEST_URI[0] = rtrim($exploded_REQUEST_URI[0],"/")."/".$filename;
      $url = implode("?", $exploded_REQUEST_URI);
      header("Location: ". $url, true, 307);
      return;
    }
  }
}

ini_set('default_charset', NULL);
$ext = pathinfo($requestedAbsoluteFile, PATHINFO_EXTENSION);
if (preg_match('/^(php|phtml|phtm)$/', $ext)) {
  $dir = getcwd();
  chdir(dirname($requestedAbsoluteFile));
  include($requestedAbsoluteFile);
  chdir($dir);
} else if (preg_match('/^(html|htm)$/', $ext)) {
  readfile($requestedAbsoluteFile);
} else {
  return FALSE;
}

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Wiki内検索

フリーエリア

管理人/副管理人のみ編集できます