Jump to content

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


cpordoegr

Recommended Posts

Hi,

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?

 

Thanks.

 

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:

 

<?php
$path_to_zip = '/some/path/somefile.zip';
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".filesize($path_to_zip));
header("Content-Disposition: attachment; filename=yourfile.zip");
readfile($path_to_zip);
exit;
As you can see most of this code is focused on the mechanics of the HTTP protocol.

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)?

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.

 

Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.