I have an application that is generating a file, and I have that working beautifully using CURL. However, when the page reloads and the file is out there, I want to automatically trigger the download without the user having to click on the link to launch it in another window. At the moment, the closest thing I could come up with is using JavaScript to window.open, but then that pop-up window is left out there. Is there a way through PHP, or something else, where I can trigger the other URL without creating a new window?

I tried just doing another instance of CURL, but that doesn't work for my application. I have many header() clauses in the file so that it automatically downloads, and CURL returns all kinds of code on the screen... and doesn't actually download the file.

Any ideas?

    I've seen sourceforge do this and certain other sites. You load some page and something in the page...javascript or a link or reference or something...will trigger a download and you get prompted to save the downloading file somewhere.

    I think this is mostly a matter of sending the right headers. I found this with a bit of searching:

    I think the problem is that you're trying to load a file result INTO #downloadmsg, which isn't going to work because .load() is only going to load results as HTML...NOT binary data or other encoding.

    One approach that might work is creating a hidden iframe in HTML, like this:

    <iframe id="secretIFrame" src="" style="display:none; visibility:hidden;"></iframe>

    Then, set the attr of the iframe to your querystring using Javascript and JQuery:

    $("#secretIFrame").attr("src","myphpscript.php?option1=apple&option2=orange");

    and then using PHP headers to force the download when the source is set (here's an example of an exporter header set from one of my scripts that uses an octet stream):

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment;filename=data.xls ");
    header("Content-Transfer-Encoding: binary ");
    

      And then add a <noscript> section of the output with a download link, just in case. 🙂

        6 days later

        Thank you both for your input!! The iframe solution worked perfectly. And I'll include the noscript stuff, just in case. Thanks again!

          Write a Reply...