我有一个名为"viewDoc"的函数,它应该转到web根目录外的一个文件夹并为我提取一个文件。它可以连接图像(Jpgs等),但对于PDF,它只输出一个空白的灰色页面,如图所示-http://www.tutorplanner.com/userimage/viewdoc/12787622467.pdf
有人能看到我做错了什么吗?我已经为此挠头一天了!
public function viewDoc($doc) {
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$file = $doc;
$fileDir = '/var/uploads/';
if (file_exists($fileDir . $file))
{
$contents = file_get_contents($fileDir . $file);
//print_r($contents);
header('Content-Type: ' . mime_content_type($fileDir . $file));
header('Content-Length: ' . filesize($fileDir . $file));
readfile($contents);
}
}
readfile与文件名的参数一起使用,而不是文本。
两个可行的示例(file_get_contents):
public function viewDoc($doc) {
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$file = $doc;
$fileDir = '/var/uploads/';
$filePath = $fileDir . $file;
if (file_exists($filePath))
{
$contents = file_get_contents($filePath);
header('Content-Type: ' . mime_content_type($filePath));
header('Content-Length: ' . filesize($filePath));
echo $contents;
}
}
或(readfile):
public function viewDoc($doc) {
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$file = $doc;
$fileDir = '/var/uploads/';
$filePath = $fileDir . $file;
if (file_exists($filePath))
{
header('Content-Type: ' . mime_content_type($filePath));
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
}
}
我还为您添加了$filePath
变量,因为没有理由多次连接字符串。
编辑
作为额外的安全性,根据Yazmat的评论,您可以使用$file = str_replace(array('..', '/'), '', $doc);
,因为这将删除对其他目录的所有引用(然而,使用斜杠也会删除对子目录的访问,所以您可能需要跳过它,这取决于您的代码和文件结构)。
这里有一个很大的安全问题,任何人都可以使用您编写的函数访问服务器上的任何内容。我真的建议你不要使用它,只把你的文件(应该可以访问)放在公共网络目录上。