Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

php - Serving file hosted on another server as download

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...