繁体   English   中英

要求用户使用PHP下载文件

[英]Asking user to download file in PHP

我试图让浏览器提示用户下载文件。 但是,在尝试了堆栈溢出和Internet周围的几种方法后,由于某种原因,所有方法都以静默方式失败。 是否在现代浏览器中无法做到这一点?

我只是希望用户从服务器下载文本(.txt)文件。 我已经尝试了以下(和更多)此代码,但无济于事:

header('Content-disposition: attachment; filename=newfile.txt');
header('Content-type: text/plain');
readfile('newfile.txt');

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".txt";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

我已经尝试了PHP.NET的示例(没有一个对我有用): http ://php.net/manual/en/function.readfile.php

我设置了正确的权限,该文件存在且is_可读。 我现在不知道为什么这样做不起作用。 任何帮助都会很棒。

我为您提供一种解决方案。

假设download.php是下载文件的文件。

因此,当用户单击下载链接以显示确认对话框时,如果用户选择是,则将用户重定向到download.php ,否则下载将不会发生,例如chrome这样的浏览器会在不询问用户是否喜欢下载的情况下启动下载一个文件与否。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM