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 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?