Patrick
Patrick

Reputation: 7195

Creating and Downloading a file using PHP

I am trying to rewrite and download a .txt file when the user submits the following form, but am having a problem at the final hurdle.

<form id="saveFile" action="index.php?download" method="POST" onsubmit="return false;">
    <input type="submit" name="backupFile" id="backupFile" value="Save a file" />
    <input type="hidden" name="textFile" id="textFile" />
</form>

When the submit button is pressed I am running a jQuery function which contains the following (simplified) code - I have taken out the code of what I am actually saving and replaced it with a simple string. This sets the 'hidden' input type and then submits the form.

$("#textFile").val('This is the text I will be saving');
document.forms['saveJSON'].submit();

When the form is submitted, the following PHP code is run:

<?php 
if (isset($_GET['download'])) {

    $textData = $_POST["textFile"];
    $newTextData = str_replace("\\","",$textData);
    $myFile = "php/data.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $newTextData);
    fclose($fh);

    header("Cache-Control: public");
    header("Content-Description: File Download");
    header("Content-Disposition: attachment; filename='".basename($myFile)."'");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: binary");
    readfile($myFile);
}
?>

Up to the fclose($fh); line the code actually works fine; The .txt file has been updated with the new contents required and the file downloads. However, when I open the downloaded file, it contains the .txt file text along with a lot of the content from the web page (index.php).

For example, the file may look like this

"This is the text I will be saving

This is the h1 of my website

Followed by the rest of my content"

Does anyone know what may be causing this?

Upvotes: 0

Views: 1998

Answers (1)

Venu
Venu

Reputation: 7289

First, as Harke told, you redirect (or link) to a script that only takes care of offering the download, you can go around that easily

clean the output buffer before read file and exit the script after readfile

ob_clean();
    flush();
    readfile($file);
    exit;

Upvotes: 2

Related Questions