send a file to client - php

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.

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.

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.

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

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

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.

Related

Is there a way to generate two different text files on the fly with php?

Thanks to this topic I'm able to generate one single text file and download it on the fly. But I would like to generate two separated text files. My code seems like this:
$status = //math
if(status)
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=config.txt");
//...config text
include 'test.php';
Test.php file:
<?php
$timeout = "time";
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=timout.xml");
echo $timeout;
?>
the timeout.xml text is being included inside config.txt, generating only the timout.xml file to download. Is there a way to generate two separated text files to download on the fly?
You cant do it because HTTP doesnt support the downloading of multiple files in a single click..The best option would be zipping the files on the server and transfering it as said here.
Or you can use javascript to on the link to request two request to the server and which lets you fetch the data from the single click as #deceze and #brian said in the comment

What does the "PK¿¿¿" response means in PHP

Hi I'm downloading a file to an app on iOS using the function readfile() on a PHP web service and I want to know if the file is downloaded correctly but I don't know how I can do that.
So what I'm trying is to do some echo to know if the file has been downloaded like this:
echo "before";
readfile($file);
echo "after";
But the response I get is this:
beforePK¿¿¿
Any one knows what does this mean or how can I know if the file is downloaded correctly?
UPDATE:
Yes it's a zip file, here are my headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$ticket");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
You're trying to output the contents of a zip file aren't you?
readfile($file) works the same as echo file_get_contents($file). If you're trying to present someone a file to download, do not add any additional output else you risk breaking the file.
I would also recommend reading up on the header function. That way you can explicitly tell the browser that you're sending a file, not an HTML page that has file-like contents. (See the examples involving Content-Type)
PHP should be setting the correct headers prior to readfile() - this LITERALLY reads the file out to the browser/app... but the browser/app needs to know what to do with it...
Usually you just assume that once the connection has closed that the data is done being transferred. If you want to validate that the file has been transferred fully, and without corruption you'll need to use a data structure like XML or JSON which will:
Delimit the data fields and cause the XML/JSON parser to throw an error if one is omitted, aka the transfer was cut off before it finished.
Allow you to embed more than one piece of data with the response, eg. an MD5 hash of the file that can be re-calculated client-side to verify that the data is intact.
eg:
$file = 'myfile.zip';
$my_data = array(
'file' => base64_encode(file_get_contents($file)),
'hash' => md5_file($file)
)
//header calls
header(...)
echo json_encode($my_data);
exit;

Avoiding Request Url Too Long with PHP for a file XLS Relay Service

What i am trying to do is provide a way for an Xls file generated on the client side in js to be downloaded. So I have the xls in a string in js and need to give the user a way to download it and open it in excel.
As i understand the only way to do this is to do it on the server via the content type, so I have tried to provide a php that does a file relay... Here is the php
<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"my-data.csv\"");
$data=stripcslashes($_REQUEST['csv_text']);
echo $data;
?>
A request can end up being rather long so for example i might have this request... (actually shortened greatly).
I am not good with php, can anyone suggest a better way to modify this relay script (or better way entirely) to accomplish this?
http://myserver.com/ExcelRelay.php?csv_text=Id%09City%09Phone%09Address%201%09Address%202%09State%09Type%09Employees%09Revenue%09Leed%09Established%09Comments%09Country%09Postal%20Code%09Territory%0A3%09Greensboro%096538227668%09%0978%20Rocky%20Second%20St.%09New%20Jersey%09Remote%09%090%091%09Sun%20Aug%2009%201964%2000%3A00%3A00%20GMT-0400%20%28Eastern%20Daylight%20Time%29%09%22Et%20quad%20estis%20vobis%20homo%2C%20si%20nomen%20transit.%20%0A%20Sed%20quad%20estis%20vobis%20homo%2C%20si%20quad%20ut%20novum%20vobis
Thanks For the Response, The final script was
<?php header("Content-type: application/octet-stream");
header("Content-Disposition: attachment;filename=\"".$_POST['filename']."\"");
echo $_POST['data'];
?>
One word: POST.
Request Url Too Long is a client side error, and one that is (AFAIK) exclusive to IE, these days. If you want to send the data to the server and have it sent back to you as a file, you will have to send the data in the body of the request.
See here for more information.

Is there a way to force the user to download a file from a href link rather than to open it in a browser window?

Basically I wrote a script that generates a xml file based on user input. After the file is generated a download link appears like so:
Download File
But when clicked it opens the xml in the browser, I want it to start downloading when the link it clicked instead. Is there any way to achieve that?
Yeah, there is. It does require specifying some headers. Exactly how it works depends on what language you're using, but here's an example using php, taken off of php.net:
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
Basically, first we tell the client what type of file we're sending, then we tell the client that what we're sending is an attachment, and it's name, instead of it being a page to display, and then finally we print/read the file to the output.
Given that you're already using php to generate the xml file, I would suggest adding the header commands above to the code that generates the xml file, and see if that does the trick.
If you happen to be using Apache for your web server, and you always want to force downloading of XML files, there is a more efficient way to do what #chigley suggested. Just add the following to a .htaccess file.
<Files *.xml>
ForceType application/xml
Header set Content-Disposition attachment
</Files>
What happens when a browser sees a link is not dependent on the link, but rather on the target of the link. Your web server should send the appropriate header: Content-Disposition: attachment;filename="file.xml" to tell the browser that it should prompt to save the file instead of displaying it.
It depends on what the client computer does with XML files. If you doubleclick on a XML file, it will open in your browser probably.
download.php:
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
readfile('/path/to/file.xml');
HTML:
Download

using header() to rewrite filename in URL for dynamic pdf

I have a php script that generates a pdf report. When we go to save the pdf document, the filename that Acrobat suggests is report_pdf, since the php script is named report_pdf.php. I would like to dynamically name the pdf file, so I don't have to type the appropriate name for the report each time that I save it.
Asking on a news group, someone suggested this, where filename="July Report.pdf" is the intended name of the report
<?
header('Content-Type: application/pdf');
header('Content-disposition: filename="July Report.pdf"');
But it doesn't work. Am I doing it wrong, or will this work at all? Is this a job for mod_rewrite?
So I've tried both
header('Content-disposition: inline; filename="July Report.pdf"');
and
header('Content-disposition: attachment; filename="July Report.pdf"');
( not at the same time ) and neither work for me. Is this a problem with my web host? For this url, here's my code:
<?
header('Content-disposition: inline; filename="July Report.pdf"');
// requires the R&OS pdf class
require_once('class.ezpdf.php');
require_once('class.pdf.php');
// make a new pdf object
$pdf = new Cpdf();
// select the font
$pdf->selectFont('./fonts/Helvetica');
$pdf->addText(30,400,30,'Hello World');
$pdf->stream();
?>
Try:
header('Content-Disposition: attachment; filename="July Report.pdf"');
or
header('Content-Disposition: inline; filename="July Report.pdf"');
Another option would be to use the $_SERVER['PATH_INFO'] to pass your "July Report.pdf" - an example link might be:
<a href="report_pdf.php/July%20Report.pdf?month=07">
That file should default to saving as "July Report.pdf" - and should behave exactly like your old php script did, just change the code that produces the link to the pdf.
Should be:
header('Content-disposition: attachment;filename="July Report.pdf"');
Based on https://github.com/rospdf/pdf-php/raw/master/readme.pdf (Page 19)
The stream-method accepts an array as parameter:
stream([array options])
Used for output, this will set the required headers and output the pdf code.
The options array can be used to set a number of things about the output:
'Content-Disposition'=>'filename' sets the filename, ...
This code works well for me
$ezOutput = $pdf->ezStream(array("Content-Disposition"=>"YourFileName.pdf"));
In my case I use ezStream() but I think stream() should give the same result.
For the name shown on the title tab in the browser
I had the same problem, then i found that it's metadata missing inside my .pdf.
I used a tools ("debenu PDF tools") for edit pdf property like author, title, etc...
I just change title from empty field to what title I want, upload the new pdf and now, with same code, same script the browser show the right name!
For the name when u ask to save document
is what u specify in header filename=
Did you try to remove spaces from file name using hyphens? So, I think its name must be like this; filename=July-Report.pdf

Categories