0

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?

1
  • 1
    You are outputting it that way. If you stop doing so, it won't happen. If you redirect (or link) to a script that only takes care of offering the download, you can go around that easily. Commented Oct 15, 2012 at 9:00

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! Adding those three lines made it work without having any redirects!! :)
yes it works! because its cleans the buffer and exits the script. first message was to give you additional info. you are welcome :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.