send a file to client

我的梦境 提交于 2019-11-26 20:26:19

问题


I want to write a text file in the server through Php, and have the client to download that file.

How would i do that?

Essentially the client should be able to download the file from the server.


回答1:


In addition to the data already posted, there is a header you might want to try.

Its only a suggestion to how its meant to be handled, and the user agent can chose to ignore it, and simply display the file in the window if it knows how:

<?php

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

See Rfc2183 for more on the Content-Disposition header.




回答2:


This is the best way to do it, supposing you don't want the user to see the real URL of the file.

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

Additionally, you could protect your files with mod_access.




回答3:


PHP has a number of very simplistic, C-like functions for writing to files. Here is an easy example:

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

It's a very basic example, but you can find more references to this sort of operation here:

PHP fopen




回答4:


If you set the content type to application/octet-stream, the browser will ALWAYS offer file as a download, and will never attempt to display it internally, no matter what type of file it is.

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

  // output file content here
?>



回答5:


Just post a link on the site to http://example.com/textfile.php

And in that PHP file you put the following code:

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

That way you can create the content dynamic (from a database)... Try to Google to oter "Content-Type" if this one is not the one you are looking for.



来源:https://stackoverflow.com/questions/737045/send-a-file-to-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!