0

当用户提交以下表单时,我正在尝试重写和下载 .txt 文件,但在最后一关时遇到了问题。

<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>

当按下提交按钮时,我正在运行一个 jQuery 函数,其中包含以下(简化的)代码 - 我已经取出了我实际保存的代码并将其替换为一个简单的字符串。这将设置“隐藏”输入类型,然后提交表单。

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

提交表单后,将运行以下 PHP 代码:

<?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);
}
?>

直到 fclose($fh); 行代码实际上工作正常;.txt 文件已使用所需的新内容进行更新,并且文件已下载。但是,当我打开下载的文件时,它包含 .txt 文件文本以及来自网页的大量内容(index.php)。

例如,文件可能如下所示

“这是我要保存的文本

这是我网站的h1

接下来是我的其余内容”

有谁知道可能是什么原因造成的?

4

1 回答 1

2

首先,正如 Harke 所说,您重定向(或链接)到只负责提供下载的脚本,您可以轻松地绕过

在读取文件之前清理输出缓冲区并在读取文件之后退出脚本

ob_clean();
    flush();
    readfile($file);
    exit;
于 2012-10-15T09:00:06.230 回答