duanci9305 2011-03-26 03:55
浏览 30
已采纳

托管在另一台服务器上托管的文件作为下载

I have a simple, yet critical question (critical for my application)

I will have a file url as:

http://a.com/b.jpg
http://a.com/b.zip
http://a.com/b.mp3
<or any valid file>

When user will click on download link for any specific file (say b.jpg) on my site i.e., b.com, user will see url as

http://b.com/?f=1

I don't want user to see original URL and secondly, want to force download of file, irrespective of filetype

I know that I can achieve this using readfile (Check Example1 at http://php.net/manual/en/function.readfile.php), but I don't know filesize and mimetype, how can I get assurance that file will be downloaded properly?

Please help guys

  • 写回答

2条回答 默认 最新

  • dongzhiyi2006 2011-03-26 04:03
    关注

    I suppose you can use cURL to fire off a HEAD request for the target URL. This will let the web server hosting the target the mimetype and content length of the file.

    $url = 'http://www.example.com/path/somefile.ext';
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    curl_setopt($ch, CURLOPT_NOBODY, true); // make it a HEAD request
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $head = curl_exec($ch);
    
    $mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    $path = parse_url($url, PHP_URL_PATH);
    $filename = substr($path, strrpos($path, '/') + 1);
    
    curl_close($ch); 
    

    Then, you can write back these headers to the HTTP request made on your script:

    header('Content-Type: '.$mimeType);
    header('Content-Disposition: attachment; filename="'.$filename. '";' );
    header('Content-Length: '.$size);
    

    And then you follow this up with the file contents.

    readfile($url);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路