在Web根文件夹之外提供文档. [英] Serving documents outside the web root folder.

查看:84
本文介绍了在Web根文件夹之外提供文档.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"viewDoc"的函数,该函数应该转到网络根目录之外的文件夹并为我获取文件.它可以与图像(Jpgs等)正常工作,但是与PDF一样,它仅输出空白的灰色页面,如此处所示- http://www.tutorplanner.com/userimage/viewdoc/12787622467.pdf

I have a function called "viewDoc" which is supposed to go to a folder outside the web root and fetch a file for me. It seams to work ok with images (Jpgs etc) but with PDF's it just outputs a blank gray page as demonstrated here - http://www.tutorplanner.com/userimage/viewdoc/12787622467.pdf

任何人都可以看到我在做错什么,因为我已经为此努力了一天!

Can anyone see what I'm doing wrong as I've been scratching my head over this for a day!

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 与文件名的参数-非文本一起使用.

readfile is used with the parameter of a file name - NOT text.

两个有效的示例(file_get_contents):

Two examples that would work (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;
        }
}

或(读取文件):

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变量,因为没有理由多次连接该字符串.

I also added the $filePath variable for you, as there's no reason to concat the string multiple times.

修改

作为额外的安全性,您可以使用$file = str_replace(array('..', '/'), '', $doc);作为Yazmat的注释,因为这将删除对其他目录的所有引用(但是,使用斜杠也将删除对子目录的访问,因此您可能要跳过它,取决于在您的代码和文件结构上).

As extra security, to Yazmat's comment, you can use $file = str_replace(array('..', '/'), '', $doc); as this would remove all references to other directories (however, with the slash it would also remove access to sub directories, so you might want to skip that, dependend on your code and file structure).

这篇关于在Web根文件夹之外提供文档.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆