Susi Cox Susi Cox -4 years ago 77
PHP Question

Php Textbox output is printing instead of downloading

This problem is different of the other question problem. That problem was about IF condition. But this problem, instead of downloading file, it is printing on next page. Please don't confuse this question with other.

I have wrote a script which download output of text box. This script works fine on local server, it download the file successfully but when i put script on live server, the download file does not work. When "download output" button is clicked, instead of downloading file the output of page is shown on next page. See live script here.. http://www.globalitsoft.net/scripts/test.php

Here is the code of script.

<?php

error_reporting(0);
$mytext = "";

$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output = array();

if(isset($_POST["submit"]) || isset($_POST["download"]) ) {
for($i=0;$i<count($text);$i++) {
$output[] .= trim($text[$i]) . ' AAAAA'.PHP_EOL;
}
}

if(isset($_POST["download"]) ) {
ob_clean();
$filename = "file-name-" .date('mdY-His'). '.txt';
$handle = fopen('php://output', "w");
fwrite($handle, implode($output));
fclose($handle);
header('Content-Description: File Transfer');
header("Content-type: application/force-download");
header("Content-Type: application/octet-stream charset=utf-8");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen(implode($output)));
readfile($filename);

exit();
}
?>


<form method="POST" action="test.php">
<textarea name="inputtext" rows="10" cols="100" placeholder="Enter Any Text!" required><?php if(!empty($_POST["inputtext"])) { echo $_POST["inputtext"]; } ?></textarea>
<br><br>
<input type="submit" name="submit" value="Do it!">
<br><br>
<p>Output goes here. </p>
<textarea name="oputputtext" rows="10" cols="100" ><?php echo implode($output);?></textarea>
<input type="submit" name="download" value="Download Output">
</form>

Answer Source

This works for me:

$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);

header('Content-Type: application/octet-stream');
//You dont need to enclose the filename value in quotes
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download