How to upload files using PUT instead of POST with PHP
Pergunta
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.
Solução
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);
?>
Outras dicas
There is an example of this in the PHP Manual: File Upload: PUT Method.
<?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);
?>