Page 1 of 1

How to make browser download a file (binary) through php?

Posted: Mon Jun 02, 2003 11:22 am
by Galt
Right now I have in file getfile.php

Code: Select all

<?

// some code to get the filename from a db
// and $_GET['file_id'] is used to query db

//create filename with path
$file="../../../downloads/".$db_row['filename'];

//send headers
header("Content-Type: application/pdf");
readfile($file);

?>
This code is causes IE to display the "File Download" window, but it also shows another window on top that says "Internet Explorer cannot download file getfile.php?ID=7 from http://www.my-site.com". I have double checked the path, and its correct. I know because if I remove the header() line, the binary stuff in the file is shown in the explorer window.

Anybody know what error I'm making and how to fix it?

Thanks.

Posted: Tue Jun 03, 2003 8:00 am
by Galt
Anybody?

Posted: Tue Jun 03, 2003 9:05 am
by Takuma
How about just redirecting to them?

Posted: Tue Jun 03, 2003 10:19 am
by discobean
I havn't used the readfile function, the last passthru I done was this way:

Code: Select all

<?php
if(!($fp = fopen($filename, "rb"))) // rb for read/binary
  die("Failed to open " . $filename);
else
{
   header("Content-type: application/pdf"); // or whatever
   fpassthru($fp);
   fclose($fp);
}
?>
I think you need rb for windoze, but only r for linux...

Let me know how this goes.

Oh one more thing, I've noticed if u use cookies or sessions, applications like excel (dunno about application/pdf) won't actually send out cookies when they retrieve the file... (I would have thought the browser saves & excel opened, but not so it seemed in my case).

Does that make sense? If not, and you DO use some sort of login authority to view this pdf, then try NOT doing any security checks.

PS. I havn't tested it or anything so hopefully my memory serves me right and the syntax is ok