0

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

Jon
  • 428,835
  • 81
  • 738
  • 806
I-M-JM
  • 15,732
  • 26
  • 77
  • 103
  • possible duplicate of [Generate download file link in PHP](http://stackoverflow.com/questions/1968106/generate-download-file-link-in-php) – Jonah Mar 26 '11 at 04:00
  • I don't think this is a dupe if the OP is asking how to be an intermediary between the user and the server at `a.com`. – Jon Mar 26 '11 at 04:05
  • @Jon: [this answer](http://stackoverflow.com/questions/531292/any-way-to-force-download-a-remote-file/531294#531294) states that `readfile()` can accept a remote location as the filename argument. And the OP here says the only trouble he's having is with the mimetype and file size. – Jonah Mar 26 '11 at 04:08
  • 2
    @Jonah: The "dupe" question is no help at all on getting the size and MIME type of a file *hosted on another server*. – Jon Mar 26 '11 at 04:19
  • @Jon: Ah, I see. You're right. – Jonah Mar 26 '11 at 04:23

2 Answers2

3

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);
multimediaxp
  • 9,348
  • 13
  • 49
  • 80
Jon
  • 428,835
  • 81
  • 738
  • 806
0
  1. store file outside web root
  2. filesize(filename) will get the file size
  3. as your forcing download you don't need to know the mime type