EdwardBlack EdwardBlack - 9 days ago 6
Javascript Question

How to return string to client after setting header

I have a download button on my client side.
After the button was clicked, some headers are set on the server with PHP to initiate the download.

//code snippet:
$filename = basename($datei);

$size = filesize($datei);
$this->response->setHeader('Content-Type', "application/force-download", TRUE);
$this->response->setHeader('Content-Disposition', 'attachment; filename='.$filename , TRUE);
$this->response->setHeader('Content-Length', $size, TRUE);

return "TEST"; //<--code will never go this far, it is ignored


The download works. But I never get something returned as response but the header.
How can I return something e.g. a string, after the download was initiated?

It seems to be impossible to return something to the client after setting the header.




BACKGROUND

Basically my goal was to show and hide a spinner icon, e.g. show a spinner icon inside the download button while the file is still downloading, and hide it again after it has finished downloading.
Therefor to know if the download has finished, I thought I can just return something from the server to the client, to let the client know it, e.g. "download succeeded".

But im not sure if this would work anyway, maybe the response would arrive before the download has even finished.

Answer

You can not. Don't waste your time trying to look for a hack, rather design your download page accordingly.

When you tell a browser (using headers) that you are going to provide a file to download like here

$this->response->setHeader('Content-Type', "application/force-download", TRUE);

Then all fairly recent browsers will follow that advice and download the file, after that they don't care if PHP manages to echo something at the end or not, they don't need it.

Your PHP code is not being ignored, it is processing just fine. PHP does not stop you from having any code after you provide some headers for the browser. Its just that once you have told the client that you are going to return a file to download it does not bother what other text you wanted to output. In fact that would be considered part of the download file. You don't see it in your file because its a return which is not useful in this content, try an echo.

When you provide a Content Type header then you are expected to send the content exactly of that type if you want the browser to successfully understand your server's response.

Look at all the major download sites, almost all of them have their downloads setup so that when you click a download link you are redirected to another page which says "Your download will begin shortly..." and meanwhile they initiate another request to their download page which does just that; provides the file to download.

So in one request you can't mix the two together successfully with any fair amount of browser compatibility.

Comments