dongxianghui3709
2016-07-01 12:43
浏览 46
已采纳

使用PHP的纯文本下载显示在浏览器窗口中,而不是下载

In a kind of "step-by-step" / "wizard" setup I try to send a newly created plain text file to the user.

Problem ist that on localhost (windows, xampp) it works as intended but executed on the remote machine (hosted webspace) it gives the file contents as plain text in the browser window. (tested with same browser: chrome)

The file is a plain text file with a database backup inside (only a few entrys, not big) and was created one step before the download. Next step is deleting it and that works fine too. File itself is valid and all handles closed. Contents shown in the browser are the actual file with all lines.

$_POST sanitizing comes when download works, for simplifications unsanitized atm:

<?php
require_once('CSettings.php');
$s = new CSettings();
$file = $_POST['file'];

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header("Pragma: public");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header('Content-Length: ' . filesize($file));
    readfile($file);
}

?>

<form action="index.php" method="post" accept-charset="UTF-8">
    <input type="submit" value="Delete backup file from the server" class="btn_red">
    <input type="hidden" value="<?php echo $file; ?>" name="file">
    <input type="hidden" value="delete_backup" name="view">
</form>

Any suggestions? Fiddled around with content types already to no avail. Last resort would be zipping the whole file and try again but that would make it unnecessary complicated.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douquejituan938904 2016-07-01 12:56
    已采纳

    One solution that may work is to use the download html attribute, However, it doesn't seem to be supported in Safari.

    Download file when clicking on the link (instead of navigating to the file):

    <a href="/images/myw3schoolsimage.jpg" download>

    From: http://www.w3schools.com/tags/att_a_download.asp

    This however may require you to put the download in a separate script.

    You may also look here: How to Automatically Start a Download in PHP?

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题