Sanitizing File Paths in PHP

删除回忆录丶 提交于 2019-12-11 04:35:25

问题


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.



来源:https://stackoverflow.com/questions/9385267/sanitizing-file-paths-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!