我有一个HTML选择表单,它用数据库中的元素填充我的列表,如下所示:
<form action="" method="POST">
<select name="item_select">
<?php
$query = "SELECT * FROM files_table";
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)) {
?>
<option value=<?php echo $row->id; ?> > <?php echo $row->file_name; ></option>
<?php }// end while?>
</select>
<br /><br />
<input name="show_png" type="submit" value="Show" />
<input name="delete" type="submit" value="Delete" />
<input name="download_text" type="submit" value="Download .txt File" />
<input name="download_image" type="submit" value="Download .png File" />
</form>
我有表单的"显示"answers"删除"按钮的功能,可以显示和删除存储在数据库中的内容。然而,我很难找到让用户下载文件的方法。现在,我的基本策略是:
if (isset($_POST['download_text'])) {
// Code to create .txt file from content (omitted).
// File name of content stored in $file_name variable.
// Download file.
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="sample.txt"');
readfile($file_name);
}
这类工作。我的意思是,我下载了一个包含内容的文件,但问题是,我还看到了该内容后面的纯文本html表单。有没有办法确保这种情况不会出现?
readfile
之后的die()
。
我真的不明白你的问题在哪里——实际上你的代码运行得很好。我已经测试过了,文件下载时没有任何HTML内容。谢谢,