How do I make sure a file path is within a given subdirectory?

前端 未结 3 1374
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 02:19

I want to make sure a file path set via query string does not go outside of the desired subdirectory. Right now, I am checking that:

  1. The path does not start w
相关标签:
3条回答
  • 2021-01-13 02:40

    The use of realpath should not change the path, so I use it in the following way:

    function checkPath($pathToCheck) {
        global $basepath;
        $fullpath = $basepath.'/'.$pathToCheck;
        if ($fullpath==realpath($fullpath) && is_dir($fullpath)) {
            return $fullpath;
        } else {
            error_die('path not allowed: '.htmlentities($pathToCheck));
        }
    }
    
    0 讨论(0)
  • 2021-01-13 02:52

    Call

    $path = realpath("sample/$path");
    

    Then check that the resulting path starts with the directory you're expecting.

    0 讨论(0)
  • 2021-01-13 03:00
    <?php
        // Current path information
        $path = $_GET['path'];
        $vroot = "sample";
    
        // Validate that the $path is a subfolder of $vroot
        $vroot = realpath($vroot);
        if(substr(realpath($path), 0, strlen($vroot)) != $vroot or !is_dir($path)) {lid!
            exit("Invalid path");
        } else {
           echo "Ah, everything is alright!";
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题