在PHP中从根目录上方的路径访问文件

在PHP中从根目录上方的路径访问文件,php,download,Php,Download,我正在用PHP编写一个简单的上传/下载页面。通过下面的代码,我可以看到文件是根目录上方文件夹的内容,但无法访问这些文件。原因可能是什么 $targetdir="/../cat/"; if ($dir = @opendir($targetdir)) { while ($file = readdir($dir)) { if ($file != "." && $file != "..

我正在用PHP编写一个简单的上传/下载页面。通过下面的代码,我可以看到文件是根目录上方文件夹的内容,但无法访问这些文件。原因可能是什么

$targetdir="/../cat/";    
if ($dir = @opendir($targetdir))
        {
            while ($file = readdir($dir))
            {
                if ($file != "." && $file != "..")
                echo "<td><a href=".$targetdir.$file.">".$file."</a></td>";
            }
            closedir($dir);
        }
$targetdir=“/../cat/”;
如果($dir=@opendir($targetdir))
{
而($file=readdir($dir))
{
如果($file!=“&&&$file!=”)
回声“;
}
closedir($dir);
}

您无法访问web根目录上方的文件,而是需要编写一个脚本来执行此操作

downloadfile.php?file=somefile.txt


当我更改它时,它不再打印文件列表。此外,即使我在打印列表时硬编码“/”,并在文件的直接链接中跳过它,也不会改变任何东西。哎呀,我误解了这个问题,因为@garryp提到这是一个安全问题。您需要使您的Web服务器运行的用户和/或组具有写入该目录的权限。我可以写入该目录,因为my.php的上载部分工作正常。哇,请永远不要这样做。这将允许任何人访问您服务器上的任何可读文件。@JonStirling当然,如果这是downloadfile.php中唯一的内容,那将非常糟糕,正如我在代码下面直接提到的。我不这么认为,因为我也实现了上载,这项工作非常好。你确定吗?我非常确定大多数服务器上的安全策略都会阻止您超越根。@garryp这里的问题不是安全性,而是它正在尝试这样做。。。您需要这些文件存在于webroot之外,而不是直接存储在web可访问的位置,这有什么原因吗?很遗憾,是的,这是必需的。我希望由我来决定
<?php

$file = $_GET['file']; 

if (strpos($file, '..') !== false) {
    throw new \Exception('Illegal path requested');
}

/** 
 * this will restrict files to this directory or above as 
 * to not allow reading of files which you do not want a user to access
 */
$basePath = __DIR __ . '/../cat';

$fullPath = sprintf('%s/%s', $basePath, $file);

/** check to see if the file exists and is readable **/
if (false === is_readable($fullPath)) {
    throw \Exception('file does not exist or is not accessible');
}

echo file_get_contents($file);
exit;
/** relative to the file that started the execution **/
$targetdir = "../cat/"

/** relative to the file that contains this variable declaration**/
$target = __DIR__ . "/../cat/"