Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download msg file with PHP

Tags:

php

I'm currently creating a feature that would allow to download files from remote server. My script works fine for all file types required but it doesn't work for the msg files for some reason (It downloads empty file (0K)). Same behavior in Chrome and IE by the way. I thought the problem is with file size so I've tested to download large zip file and it also work fine, seems that only msg files I've got issue with.

My script:

// Get parameter form html page
if(isset($_GET['file_name'])) $file_name = $_GET['file_name'];

$file_name = str_replace('"', '\\"', $file_name);
$file_url = 'http://mypath/uploads/' . $file_name;

header('Content-Type: application/octet-stream');
header("Content-disposition: attachment; filename=\"".$file_name."\"");
header("Content-Transfer-Encoding: Binary");

readfile($file_url);
exit;

What I'm doing wrong?

P.S. I think possible solution is to archive (zip) .msg file during uploading process and then download it as .zip instead but I'm looking for a better solution.

like image 458
Deniss Muntjans Avatar asked Dec 24 '22 20:12

Deniss Muntjans


2 Answers

Expanding my comment into an answer:

I tested your script with a local file, eg. $file_url = 'test.msg';, and this is working here. So I suspect that there is a problem getting the file from the remote server. Can you download the remote .msg file from the server where your PHP script is running by other means than PHP, eg. with wget http://mypath/uploads/test.msg? You could also check the return value of readfile - if it is false, there is an error reading the file. If you cannot download the file or if readfile returns false, then the problem is not in your code, but a server configuration or connectivity issue, which you have to fix first.

Regarding your code: you should sanitize your $_GET['file_name'], to avoid someone passing stuff like ../passwd.

like image 64
ax. Avatar answered Dec 26 '22 15:12

ax.


Try use another content-type:

header("Content-Type: application/download");
like image 32
el3ien Avatar answered Dec 26 '22 15:12

el3ien