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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真