Christoph Grimmer
Christoph Grimmer

Reputation: 4313

How to send a string as file to the browser using php?

I want to create a file in memory and send it to the browser when a button is clicked. I was expecting the following code to do the trick:

<?php

$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;

?>

Instead I get the string echoed. What's my stupid newb error?

Upvotes: 1

Views: 7764

Answers (2)

viDim
viDim

Reputation: 11

"Remember that header() must be called before any actual output is sent" (c)

Upvotes: 1

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

You need to change your content type, this works for me, tested on FF and Chrome

<?php 
$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: text/plain');//<<<<
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;
?>

Upvotes: 4

Related Questions