LoginSignup
3
3

More than 5 years have passed since last update.

Linux上の相対パス表記を絶対パス表記に変換するPHPスクリプト

Posted at

相対パスから正しい絶対パスへ変換するというのではなく、あくまで表記を変更するのみ。ユーザー指定のパスのファイルを読み込む際に、相対パスを許すと想定しないファイルを呼び出されたりする(ディレクトリトラバーサル攻撃)のでその対策用関数。

example.php
function pathChange($file_path) {
    $file_path = str_replace(array("..", "./"), "", $file_path);
    $file_path = array_merge(array_diff(explode("/", $file_path), array("")));
    return "/" . implode("/", $file_path);
}

「..」や「./」の表記は削除し、「/」で分解の上、空になった要素を配列内から削除し、それを再度/で結合しなおして返すという処理。

実行例)
../../etc/passwd => /etc/passwd
./foo///bar/..hoge.php => /foo/bar/hoge.php

ただし、本当に存在するパスを生成する可能性がある(/etc/passwdとか)ので、利用する際には読み込むファイルパスを想定しているベースディレクトリと結合させたファイルパスにするとか工夫はいると思いますが。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3