使用PHP创建和下载文件 [英] Creating and Downloading a file using PHP

查看:120
本文介绍了使用PHP创建和下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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();

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

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

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

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

这是我将要保存的文本

这是h1我的网站

其余的内容后跟

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

Does anyone know what may be causing this?

推荐答案

首先,正如Harke所说,您将重定向(或链接)到仅提供下载的脚本,可以轻松解决

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

在读取文件之前清理输出缓冲区,并在readfile

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

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

这篇关于使用PHP创建和下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆