如何在PHP中使用PUT而不是POST上传文件


How to upload files using PUT instead of POST with PHP

我正在构建我的第一个RESTApi,到目前为止进展顺利,我只是遇到了通过PUT请求方法上传文件的问题。我需要成为PUT,因为我正在从iOS应用程序更新用户和他们的化身图像,PUT专门用于更新请求。

所以当我PUT和文件上传时,$_FILES数组实际上是空的,但当我打印PUT数据时

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

我得到以下回应;

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

)

现在我真的不理解这个PUT数据,因为我不能像访问数组或任何东西一样访问它。所以我的问题是如何从PUT数据访问上传的文件?

谢谢你的帮助。

PHP支持某些客户端在服务器上存储文件时使用的HTTP PUT方法。PUT请求比使用POST请求上传文件简单得多,它们看起来像这样:

PUT /path/filename.html HTTP/1.1

以下代码在官方PHP文档中,用于通过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);
?>

PHP手册中有一个这样的例子:文件上传: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);
?>