简体   繁体   English

要求用户使用PHP下载文件

[英]Asking user to download file in PHP

I am trying to get the browser to prompt the user to download a file. 我试图让浏览器提示用户下载文件。 However, after having tried several methods from stack overflow and around the Internet, for some reason all are silently failing. 但是,在尝试了堆栈溢出和Internet周围的几种方法后,由于某种原因,所有方法都以静默方式失败。 Is it the case that this just isn't possible in modern browsers? 是否在现代浏览器中无法做到这一点?

I'm simply wanting the user to download a text (.txt) file from the server. 我只是希望用户从服务器下载文本(.txt)文件。 I've tried this code below (and more) to no avail: 我已经尝试了以下(和更多)此代码,但无济于事:

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); 

I have tried the examples from PHP.NET (none of which are working for me): http://php.net/manual/en/function.readfile.php 我已经尝试了PHP.NET的示例(没有一个对我有用): http ://php.net/manual/en/function.readfile.php

I have the correct permissions set, the file exists and is_readable. 我设置了正确的权限,该文件存在且is_可读。 I'm now left scratching my head as to why this isn't working. 我现在不知道为什么这样做不起作用。 Any help would be great. 任何帮助都会很棒。

I have one solution for you. 我为您提供一种解决方案。

Lets assume download.php is the file that downloads the file. 假设download.php是下载文件的文件。

So when the user clicks on the link to download show a confirm dialog, if the user selects yes then re direct the user to download.php or else download will not occur some browsers like chrome starts the download without asking users if they like to download a file or not. 因此,当用户单击下载链接以显示确认对话框时,如果用户选择是,则将用户重定向到download.php ,否则下载将不会发生,例如chrome这样的浏览器会在不询问用户是否喜欢下载的情况下启动下载一个文件与否。

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

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