Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files using PUT instead of POST with PHP

I'm building my first REST Api and it's going well so far, i'm just having an issue with files uploads via PUT request method. I need to be PUT because i'm updating a user and their avatar image from an iOS app, and PUT is specifically for update requests.

So when I PUT and file upload, the $_FILES array is actually empty, but when I print the PUT data

parse_str(file_get_contents('php://input'), $put_vars);  
$data = $put_vars; 
print_r($data);

I get the following response;

Array
(
    [------WebKitFormBoundarykwXBOhO69MmTfs61
Content-Disposition:_form-data;_name] => \"avatar\"; filename=\"avatar-filename.png\"
Content-Type: image/png

�PNG


)

Now I don't really understand this PUT data because I can't just access it like an array or anything. So my question is how do I access the uploaded file from the PUT data?

Thanks for your help.

like image 872
Wasim Avatar asked Sep 09 '12 16:09

Wasim


People also ask

How do I send a file in Put request in the postman?

Use Postman In Postman, create a new PUT request and include your newly created API call in the request. On the Body tab, and select binary. Select the file you would like to upload. Click Send.

Which PHP function is used to upload files?

enctype="multipart/form-data": This value refers to the content type of the files that will be accepted for uploading. It also indicates the type of encoding that the PHP script will use for uploading. The multipart/form-data value enables us to upload files using the POST method.

What is put method in PHP?

PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this: PUT /path/filename.html HTTP/1.1.


1 Answers

PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this:

PUT /path/filename.html HTTP/1.1

The following code is in the official PHP documentation for uploading files via PUT:

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
   and write to the file */
while ($data = fread($putdata, 1024))
  fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>
like image 200
Greg Avatar answered Sep 30 '22 02:09

Greg