Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to trigger a file download (in PHP)?

Quick (and hopefully easy) question: I need to trigger a download of a PDF file that's generated by a PHP file. I can do this:

<a href="download.php">Download</a>

but should I be doing this another way? Javascript maybe? The above works but the window shows "Loading..." until the download starts. I'd like to provide some feedback to the user that something is happening.

Ideas?

Note: I already have the code that sends the file from the server. It works perfectly. This question is simply about how best to call that script from the client.

Some sites have downloads that automatically start. How do they do that?

The problem with a direct URL is that if the PHP script errors it'll replace th econtent of the existing page, which is not what I want.

like image 718
cletus Avatar asked Jan 15 '09 05:01

cletus


People also ask

How do I trigger a download in HTML?

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.

Which one of the following function is used to download a file in PHP?

The readfile() function is used in PHP script to forcibly download any file of the current location, or the file with the file path.


2 Answers

EDIT

Yes javascript, something like:

<a href="download.php" onclick="this.innerHTML='Downloading..'; downloadPdf(this);">Download</a>

If you need to actually understand when the download is started you probably need to call an iframe and then use the "onload" event on it.. for example:

// javascript
function downloadPdf(el) {
    var iframe = document.createElement("iframe");
    iframe.src = "download.php";
    iframe.onload = function() {
        // iframe has finished loading, download has started
        el.innerHTML = "Download";
    }
    iframe.style.display = "none";
    document.body.appendChild(iframe);
}
like image 137
Luca Matteis Avatar answered Sep 30 '22 11:09

Luca Matteis


The solution you have for download is fine. You may want to consider some visual feedback to the user, perhaps by using javascript to show a "Downloading, please wait message" on the current page when the link is clicked via an onclick handler. Or simply indicate that the download may take some time to start next to the link. Since IE will unload the page, stopping any GIF animations, I prefer text indications for file downloads.

like image 38
tvanfosson Avatar answered Sep 30 '22 10:09

tvanfosson