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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Galt
Forum Newbie
Posts: 18
Joined: Thu May 22, 2003 8:08 am

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

Post 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.
Galt
Forum Newbie
Posts: 18
Joined: Thu May 22, 2003 8:08 am

Post by Galt »

Anybody?
User avatar
Takuma
Forum Regular
Posts: 931
Joined: Sun Aug 04, 2002 10:24 am
Location: UK
Contact:

Post by Takuma »

How about just redirecting to them?
User avatar
discobean
Forum Commoner
Posts: 49
Joined: Sun May 18, 2003 9:06 pm
Location: Sydney, Australia
Contact:

Post 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
Post Reply