du8442 2016-08-01 23:29
浏览 28
已采纳

使用数据库字符串访问文件有问

I am having a problem accessing a file on my web server after restructuring the routes. After restructuring the files to download are stored in the address :

http://mysite/submission/uploads/test.txt

Previously it was stored in:

http://mysite/uploads/test.txt

and so the path /uploads/test.txt would work when reading from the database. Iv recently updated the routes as visible in the first sample and have updated the content in the mongodb database. However as the uploads folder is in root and the download.php file is in the submission folder the path from the database im assuming points to:

http://mysite/mydownloadpage/submission/uploads/test.txt

in my database it contains the text to the path exactly as follows:

submission/uploads/test.txt

I tried to append the prefix to the string to point up a directory back to root, but it does not function:

../submission/uploads/test.txt

This seems to result in it including the '..' instead of pointing it to the root directory.

Here is the download function which gets passed the path from the database:

function download($path){

if(!file_exists($path)){
die('Error');
}else{
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Type: application/octet-stream');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
ob_start();
flush();
readfile($path);
exit;
}
}
if (isset($_GET['download'])) {
if (!empty($_GET['download'])) {
$file = $_GET['download'];
download($file);
}
}

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • douwen8118 2016-08-02 00:44
    关注

    Alright, glad we finally got it sorted! A common practice is to define a ROOT/ROOT_PATH/etc constant that you can reference globally for all inclusions like you require. This is usually done in the root index.php file with:

    DEFINE('ROOT', getcwd());
    

    Now, there are a few issues in your current function definition. You need to supply the arguments if you want to use them. You can resolve this by amending it to:

    function download($file) { ...
                      ^^^^^--- we added this.
    

    Now, when defining your file, you need to specify the absolute path:

    $path = ROOT . DIRECTORY_SEPARATOR . $my_path_from_db;
    

    And you should note that DIRECTORY_SEPARATOR is an internal PHP defined constant which represents \ or / depending on operating system :).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄