0

I'm trying to do a simple download of a file in php. Actually it's a .csv-file, but it seems I can't even download a regular text file. I found the following code...

$mytext = "some text";
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename='whatever.txt'");
echo $mytext;

...but when I add it to my php file, there is no download being initialized, but the text of $mytext (i.e. "some text") is just simply displayed within my HTML text. I am running the whole thing in wordpress, if that might be important. Any idea?

Edit: I tried the solution from php, file download but this wasn't working at all for me. I guess, there's a problem with the headers. Since I use the php script inside my wordpress environment, I think he headers I set, are ignored - and that's why the file is interpreted as text instead as a downloadable file. Is there any way to ignore the wordpress header or force the custom header somehow?

Community
  • 1
  • 1
El_Chippo
  • 143
  • 1
  • 8

1 Answers1

0

Try this:

$mytext = "some text";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="whatever.txt"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($mytext));
echo $mytext;
Latheesan
  • 23,247
  • 32
  • 107
  • 201
  • Thanks for the respone. I tried your code, but the result is exact the same. The string "some text" is displayed on the website, in the location where the php function is called. – El_Chippo May 26 '14 at 21:06
  • I tested it on FireFox, Chrome & Internet Explorer. The file force downloads, it doesn't display. Your browser might be the issue. Have you tried it on different browser/pc? – Latheesan May 27 '14 at 09:41
  • Yess, your code is actually working and no it's not the browser - I figured out, it has something to do with wordpress. When the download function is called, I'm not able to set any headers, because all headers are already set by wordpress. I am looking for a workaround, but the whole issue seems to be quite complex as I'm kind of new to this area. – El_Chippo May 27 '14 at 09:49