Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

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とか)ので、利用する際には読み込むファイルパスを想定しているベースディレクトリと結合させたファイルパスにするとか工夫はいると思いますが。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away