将文件发送给客户端

12 php client download text-files

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

我该怎么做?

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

Ken*_*ric 14

除了已发布的数据外,您还可以尝试使用标头.

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

<?php

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

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

  • 我不知道"内容处理".谢谢(你的)信息.+1 (2认同)

Fla*_*ius 12

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

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

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


Ant*_*ony 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);
?>
Run Code Online (Sandbox Code Playgroud)

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

PHP打开