Sanitizing File Paths in PHP

2019-08-05 06:33发布

In PHP, is there a function that can perform logic similar to realpath() but on files that may not exist in the filesystem? Obviously it would not be able to resolve links etc, but my goal is to see if a path provided by a user is in a certain directory (or a sub-directory of that directory) without having to account for /.././path types of issues on my own. Calling realpath would be perfect if it did not return false when the file does not exist.

标签: php realpath
2条回答
地球回转人心会变
2楼-- · 2019-08-05 07:16

If you only need to remove the /../ a self written function wouldn't be that difficult. Just split the string onto a array, iterate over the array and insert the values in a new one. If you hit a .. remove the last element inserted in the new array. Then merge the second array back into a string.

查看更多
叛逆
3楼-- · 2019-08-05 07:29

If your concern is only files try:

function unrealpath($path){
  $rp = realpath(dirname($path));
  if( false === $rp )
    return false;
  return $rp.basename($path);
}

If you have concerns about the directories existing or not as well this won't work.

查看更多
登录 后发表回答