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

时间:2011-03-26 03:55:14

标签: php curl

我有一个简单但关键的问题(对我的申请至关重要)

我的文件网址为:

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

当用户点击我网站上任何特定文件(例如b.jpg)的下载链接时,即b.com,用户会看到网址为

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

我不希望用户看到原始网址,其次,想要强制下载文件,而不管文件类型

我知道我可以使用readfile实现这一点(在http://php.net/manual/en/function.readfile.php检查Example1),但我不知道filesize和mimetype,我怎样才能保证文件能够正确下载?

请帮助家伙

2 个答案:

答案 0 :(得分:2)

我想您可以使用cURL触发目标URL的HEAD请求。这将使托管目标的Web服务器具有文件的mimetype和内容长度。

$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); 

然后,您可以将这些标头写回到在脚本上发出的HTTP请求:

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

然后你按照文件内容进行操作。

readfile($url);

答案 1 :(得分:1)

  1. 在web root之外存储文件
  2. filesize(filename)将获得文件大小
  3. 作为您的强制下载,您不需要知道mime类型