Sanitizing File Paths in PHP

2019-08-05 07:22发布

问题:

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.

回答1:

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.



回答2:

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.



标签: php realpath