Jump to content

PHP REST API: How to Send a File as a Response.


Recommended Posts


I need some help in sending files as a response to a POST request. I have written a PHP RESt API which is already receiving files with POST requests, however i want to send back a zip file(or multiple files) in response to this request.  Any help in this regard?




Link to comment
Share on other sites

Set the mime type correctly using header() and return the data. Here's a fairly typical example ... you'd have to fill in the details regarding how/where the original file is generated:


$path_to_zip = '/some/path/somefile.zip';
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=yourfile.zip");
As you can see most of this code is focused on the mechanics of the HTTP protocol.
Link to comment
Share on other sites

Thanks for quick response.


I find that the code you provided is working. However, the client, after receiving this zip file shows the contents of the file in browser (firefox e.g.), can we enfore it to be opened with a zip software (or ask for saving it)?

Link to comment
Share on other sites

Yes i included all headers. Actually now i can identify the type of the response content on receiving side. However i want to do the following


Step 1. Create a new empty zip file

Step 2. Write the received response body (a zip file with mutliple files in it) to this zip file.


Step 1 is ok. But i am not sure how should i implement Step 2. I used "fwrite($zipfile, gzcompress($response_body));" but it is not working. Afterwards when i try to open this zip file with a zip software i get invalid zip file message.



Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.