tags:

views:

1640

answers:

2

Hello!

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 ."");
}
?>
+3  A: 

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

bucabay
I had modified script, so that user is redirected to site downloadtxt.php.Everything works fine, insted of FILENAME which user is downloading. File on a server is stored ok (filename.txt), whereas file processed from downloadtxt.php is downloaded as FIRSTWORD.txt (I guess header or sth else trims empty space between FIRSTWORD and SECONDWORD.Any idea how to get proper name filename.txt as it stored on server?EXAMPLE:fopen makes a file named by NEWStitle => My first news.txtdownloadtxt.php makes a file => My.txt (In download box is actually only "My")Thanks for help!
AnzeT
Enclose it in Quotes when adding it to the HTTP header.
bucabay