Database Reference
In-Depth Information
Discussion
Earlier sections of this chapter discuss how to incorporate the results of database queries
into web pages, to display them as paragraphs, lists, tables, or images. But what if you
want to produce a query result that the user can download to a file instead? It's not
difficult to generate the response itself: send a Content-Type: header preceding the
information, such as text/plain for plain text, image/jpeg for a JPEG image, or ap
plication/pdf or application/msexcel for a PDF or Excel document. Then send a
blank line and the content of the query result. The problem is that there's no way to
force the browser to download the information. If it knows what to do with the response
based on the content type, it will try to handle the information as it sees fit. If it knows
how to display text or images, it will. If it thinks it's supposed to give a PDF or Excel
document to a PDF viewer or to Excel, it will. Most browsers enable the user to select
a download explicitly (for example, by right-clicking or Ctrl-clicking a link), but that's
a client-side mechanism. You have no access to it on the server end.
What you can do is fool the browser by faking the content type. The most generic type
is application/octet-stream . Most users are unlikely to have any content handler
specified for it, so if you send a response using that type, it's likely to trigger a download
by the browser. The disadvantage of this, of course, is that the response contains a false
indicator about the type of information it contains. You can try to alleviate this problem
by suggesting a default filename for the browser to use when it saves the file. If the
filename has a suffix indicative of the file type, such as .txt , .jpg , .pdf , or .xls , that may
help the client (or the operating system on the client host) determine how to process
the file. To suggest a name, include a Content-Disposition: header in the response:
Content-disposition: attachment; filename=" suggested_name "
The following PHP script, download.php , demonstrates one way to produce download‐
able content. When first invoked, it presents a page containing a link that can be selected
to initiate the download. The link points back to download.php but includes a down
load parameter. When you select the link, it reinvokes the script, which sees the pa‐
rameter and responds by issuing a query, retrieving a result set, and sending it to the
browser for downloading. The header() function sets the Content-Type: and Content-
Disposition: headers in the response. (Do this before the script produces any other
output, or header() has no effect.)
<? php
# download.php: retrieve result set and send it to user as a download
# rather than for display in a web page
require_once "Cookbook.php" ;
require_once "Cookbook_Webutils.php" ;
$title = "Result Set Downloading Example" ;
# If no download parameter is present, display instruction page
Search WWH ::




Custom Search