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 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算