views:

170

answers:

1

I have a dialog box open when a user clicks on a url. In that dialog box, I have two buttons, "OK" (which closes the dialog box) and "download file" (which, I would like to have the file I just created via PHP be downloaded when clicked). How can I achieve that functionality with the "download file" button?

I tried $.get but that only retrieves the data of the file and doesn't prompt the user to download the file.

Thanks.

+1  A: 

Inside the click handler for that button:

window.location.href = "path/to/file/on/server.txt";

By the way, you don't actually have to write out a file in this case. You can use URL rewriting to make this a "virtual file", which runs your PHP code to emit the file data when accessed. You change the PHP to return the generated file data directly instead of writing it to a file.

EDIT: Virtual files in Apache:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /vfiles
    RewriteRule ~vfiles/([a-z]+)\.txt vfile-handler.php?id=$1 [L,QSA]
</IfModule>

This says that http://my.server/vfiles/foo.txt gets transparently redirected inside the Apache server to run vfile-handler.php instead, passing it "id=foo" as the query string, which you deal with just like any other GET request with a query string. Your PHP script then sets the MIME type appropriately (text/plain in this case, since we're claiming to be a .txt file) and builds the reply just as if we were building an HTML page on the fly.

Warren Young
this worked perfect! can you explain more about what you mean about using URL rewriting to create a "virtual file"?
acedanger
answered in edit above
Warren Young
he means that you'd use something like `window.location.href = "path/to/php/on/server.php?file=true"` or something similar and in your php you'd return the file if the query variable `file` is true (or some id, depending on what you need).
Blindy
Blindy, your solution can work for some cases, but it's not what I'm calling a virtual file, because it exposes to the outside world that it's actually generated by PHP. My solution hides this, being indistinguishable from a real text file you linked to directly. This can be important when you need the downloaded file to be named in a particular way, such as to leverage file associations on the target computer. If you send a virtual PDF to a browser, you want it to open in the user's PDF reader.
Warren Young
thanks for the info! I really appreciate it
acedanger