16

我想通过 Php 在服务器中编写一个文本文件,并让客户端下载该文件。

我该怎么做?

本质上,客户端应该能够从服务器下载文件。

4

5 回答 5

17

这是最好的方法,假设您不希望用户看到文件的真实 URL。

<?php
  $filename="download.txt";
  header("Content-disposition: attachment;filename=$filename");
  readfile($filename);
?>

此外,您可以使用 mod_access 保护您的文件。

于 2009-04-10T09:21:18.097 回答
14

除了已经发布的数据之外,您可能还想尝试一个标题。

它只是对如何处理它的建议,用户代理可以选择忽略它,如果知道如何处理,只需在窗口中显示文件:

<?php

 header('Content-Type: text/plain');         # its a text file
 header('Content-Disposition: attachment');  # hit to trigger external mechanisms instead of inbuilt

有关 Content-Disposition 标头的更多信息,请参阅Rfc2183

于 2009-04-10T08:37:42.337 回答
5

PHP 有许多非常简单的、类似 C 的函数用于写入文件。这是一个简单的例子:

<?php
// first parameter is the filename
//second parameter is the modifier: r=read, w=write, a=append
$handle = fopen("logs/thisFile.txt", "w");

$myContent = "This is my awesome string!";

// actually write the file contents
fwrite($handle, $myContent);

// close the file pointer
fclose($handle);
?>

这是一个非常基本的示例,但您可以在此处找到有关此类操作的更多参考:

PHP fopen

于 2009-04-10T08:28:49.783 回答
3

如果您将内容类型设置为 application/octet-stream,浏览器将始终提供文件作为下载,并且永远不会尝试在内部显示它,无论它是什么类型的文件。

<?php
  filename="download.txt";
  header("Content-type: application/octet-stream");
  header("Content-disposition: attachment;filename=$filename");

  // output file content here
?>
于 2009-04-10T08:43:06.817 回答
2

只需在网站上发布一个链接到http://example.com/textfile.php

在该 PHP 文件中,您输入以下代码:

<?php
header('Content-Type: text/plain');
print "The output text";
?>

这样您就可以创建动态内容(来自数据库)...如果这不是您要查找的内容,请尝试使用 Google 提供“内容类型”。

于 2009-04-10T08:31:34.567 回答