Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP script to download file not working in IE

I have a script that takes a key from $_GET['key'] , looks up the location in a database and uses the readfile together with some headers to present a download for the use. This works in Firefox but not IE8, haven't been able to test it on another IE. I get the following error in IE: "Internet Explorer cannot download download.php from www.example.com". As if it is trying to download the PHP script.


$the_query = "SELECT * FROM `files` WHERE `user_id`=" . $_SESSION['user_id'] . " AND `key`='" . $key . "'";

$result = mysql_query($the_query);
$row = mysql_fetch_array($result);

$file = '/var/www/vhosts/www.example.com/httpsdocs/uploads/' . $row['id'] . '/' . $row['file'];

header("Content-type: application/octet-stream");
header("Content-length: ".filesize($file));
header('Content-Description: File Transfer');
header("Cache-control: private");
header('Content-Disposition: attachment; filename=' . rawurlencode(basename($file)));
readfile($file);
like image 266
Stuart Avatar asked Aug 02 '09 13:08

Stuart


3 Answers

Set the Content-Disposition header to "attachment", like so (in PHP): where attachment was scripted.

header('Content-Disposition: attachment');

And add the following in .htaccess and add what ever extension that you want to download not only txt

<FilesMatch "\.(txt|pdf|csv|xls|xlsx|xlam|xlsb|xlsm|msg|doc|docx|mpg|jpg|png)">
   Header set Content-Disposition attachment
</FilesMatch>
like image 141
ABDULRAHMAN ALKHAMEES Avatar answered Sep 23 '22 16:09

ABDULRAHMAN ALKHAMEES


Managed to get this working by using the first example from php.net

http://us3.php.net/manual/en/function.readfile.php


header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

like image 27
Stuart Avatar answered Sep 19 '22 16:09

Stuart


To solve the error : "Internet Explorer cannot download download.php from www.example.com", Add these headers to your script:

header("Pragma: ");

header("Cache-Control: ");

The code will remove the Cache-Control from headers which makes the download problem.

The above code should be added at the top of the file.

It works fine for us.

like image 29
SequenceDigitale.com Avatar answered Sep 21 '22 16:09

SequenceDigitale.com