Force user to download .txt (php, file.txt) - php

I have a small script, which reads the data from DB, array them and save them as .txt file.
At the end, user is redirected to that file.
Now, how to achieve that when user is redirected on .txt file download box appears?
<?php
// Preden zacnemo, dobi novico iz baze!
$MOD_NEWS_SAVETXT_getnews = mysql_query("SELECT * FROM NEWS WHERE NEWSid = '{$_GET['id']}'") or die(mysql_error());
// Nardimo while in priredimo vsebino iz baze spremenljivkam!
while ($MOD_NEWS_SAVETXT_NEWSRESULT = mysql_fetch_array($MOD_NEWS_SAVETXT_getnews)) {
$MOD_NEWS_SAVETXT_FILE_name = $MOD_NEWS_SAVETXT_NEWSRESULT['NEWStitle'] . ".txt";
echo $MOD_NEWS_SAVETXT_FILE_name;
$MOD_NEWS_SAVETXT_FILE_handle = fopen($MOD_NEWS_SAVETXT_FILE_name, 'w') or die("Ne morem brati/ustvariti datoteke!");
fwrite($MOD_NEWS_SAVETXT_FILE_handle, $MOD_NEWS_SAVETXT_NEWSRESULT['NEWStext']);
fclose($MOD_NEWS_SAVETXT_FILE_handle);
header("Location: ./" . $MOD_NEWS_SAVETXT_FILE_name ."");
}
?>

This has come up before:
forcing a file to download
forcing a file download with php
How to Automatically Start a Download in PHP?
Correct way to trigger a file download (in PHP)?

To force a file to download, you have to send the HTTP Headers that will tell the browser to treat that file as a download. That is override the Content-Type of the file.
http://en.wikipedia.org/wiki/List_of_HTTP_headers
Basically, when your web server retrieves a file requested by the browser, it first checks the file extension and guesses the mime type. It then creates the HTTP response, and inserts the Content-Type header with the value of the mime-type it guessed.
You can have PHP set the content-type of the file explicitly.
The example is already given above.
header("Content-type: application/force-download");
or
header("Content-type: application/octet-stream");
For downloads, you also have to set the Content-Disposition and Content-Transfer-Encoding HTTP response headers.
These are defined in the MIME specifications: http://www.faqs.org/rfcs/rfc1521.html
It is also good to define the content-length as this allows the browser to give the user a download progress bar.
You may also want to look at using the range headers to allow request in parts.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Related

Download file size is unknown although file size is present in header

I am doing the follwoing on a web page: A click on an element sends a set of data (attached to the element) to my server which will then generate a custom zip-file:
$.post(urlprefix + 'makeZip.php', params, function(data){
window.location = urlprefix + 'getZip.php?file=' + data; //get file
}).error(handleAJAXError);
makeZip.php works just fine and returns the name of the (temporary) zip file that the client should then download. As I want to keep my server clean I route the file through another script called getZip.php which does the following:
/* RETURN REQUESTED FILE AND DELETE FROM SERVER*/
$filename = $_GET['file'];
/* TRANSFER FILE CONTENTS */
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="customDownload.zip"');
header('Content-Length: '.filesize($filename));
readfile($filename);
/* REMOVE FILE FROM SERVER */
unlink($filename);
All browsers will download the file successfully, yet I am facing one problem: the files can get rather big (up to 200MB) so I thought it would be nice to have an estimate of how long the download's going to take. That's why I am sending the Content-Length header (the specified filesize is correct). Yet, all browsers I tested this is are telling me the filesize is unknown (which might lead to the user skipping the download).
Is this some kind of problem with my header information? Is it a client-side problem? Should I use another approach to getting the client to download the file?
If the client shows "unknown filesize" in the dialog when downloading a file provided via readfile, you'd better check if mod_deflate, mod_gzip, mod_something-that-shrinks-http is installed on your server, and put an exception for given download.
More info here
EDIT by m90:
In my particular case (running Apache) I turned shrinking off by using:
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 0);
Filesize headers are sent and received correctly now in all browsers

File open/save as dialog and mime types

I am working on a simple document management system for a site - the user can upload around 20 different file types and the docs are renamed then stored in a folder above www, an entry is created in a docs table to capture meta data entered by the user and the item is then retrieved via another php file so the stored location for the files are hidden from the user.
When a user clicks to download a file using a simple a href it calls, for example, "view.php?doc=image.jpg" - when they do this currently the file opens in the browser so a jpg opens a window with pages of "wingdings" like characters etc.
I would like to be able to force a open/save dialogue box so the user decides what to do and my app doesn't try to open in the browser window with the above results.
From a previous posting I found I know I cannot pass the mime type in the "a href" tag so what other options do I have? Could I put header information into the below view.php file, for example?
$_file = $_GET['doc'];
$filename = './dir/'.$_file;
if (file_exists($filename)) {
echo file_get_contents('./dir/'.$_file);
} else {
echo "The file $_file does not exist";
}
;
You could use get_headers() to get the MIME type header of the desired file, and then use header() to output those headers into the file you're showing.
Alternatively, to simply force downloads, this:
header('Content-Description: File Transfer');
header("Content-type: application/octet-stream");
Should do it.

php save recordset to local file

I have a list of data compiled from a mysql recordset when I click a button on one of my pages. The data is stored in a variable $list.
It's a site activity log, and the button is a backup button.
Is there any way that I could make it open a SAVE AS dialogue box so I can save that data to a text file on my local comp?
when you click your "back up" button, you should get the user to a new script: this script should take the $list variable from the DB again and format it into a text file, then in order to make it available to the user's browser as a downloadable file, you should use headers (look at http://php.net/manual/en/function.header.php) like this:
<?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');
?>
In this case this is a pdf file (example is from the above link). Changing the content-type to the proper mime-type ("Content-Type: text/plain" for example) and setting the right file name, all that you echo will be sent to the browser as an attached file.
If any question, ask :)
after generate that file just set the physical path of that file and throw header so it will be download at your local system
Cheers

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

How to force a file to download in PHP

I have list of images and I want a "Download" link along with every image so that user can download the image.
so can someone guide me How to Provide Download link for any file in php?
EDIT
I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser
If you want to force a download, you can use something like the following:
<?php
// Fetch the file info.
$filePath = '/path/to/file/on/disk.jpg';
if(file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
?>
If you simply link to this script using a normal link the file will be downloaded.
Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.
In HTML5 download attribute of <a> tag can be used:
echo '<a href="path/to/file" download>Download</a>';
This attribute is only used if the href attribute is set.
There are no restrictions on allowed values, and the browser will
automatically detect the correct file extension and add it to the file
(.img, .pdf, .txt, .html, etc.).
Read more here.
The solution is easier that you think ;) Simple use:
header('Content-Disposition: attachment');
And that's all. Facebook for example does the same.
You can do this in .htaccess and specify for different file extensions. It's sometimes easier to do this than hard-coding into the application.
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
By the way, you might need to clear browser cache before it works correctly.

Categories