繁体   English   中英

如何使用 HTTP PUT 上传带有 PHP curl 的文件?

[英]How to upload a file with PHP curl using HTTP PUT?

如何使用 HTTP PUT而不是 POST 上传带有 PHP curl 的文件?

用例

假设以下示例数据...

$data = [
  'foo' = bar;
  'image_file' = curl_file_create('C:\sample.jpg','image/jpg','receipt.jpg')
];

我可以使用以下 curl 选项发布和上传上面的示例数据...

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

这导致帖子接收端的以下数据......

Array
(
    [foo] => 'bar'
    [image_file] => Array
        (
            [name] => sample.jpg
            [type] => image/jpg
            [tmp_name] => C:\tmp\php8934.tmp
            [error] => 0
            [size] => 351836
        )
)

现在,我想使用 HTTP PUT 做同样的事情。

尝试 1

如果使用以下选项更改为 http put ...

//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 

……什么都没贴。

尝试 2

如果我还将 postfields 选项更改为...

//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

帖子有效,但上传无效。 这是结果...

Array
(
    [foo] => 'bar'
    [image_file] => Array
        (
            [name] => C:\sample.jpg
            [mime] => image/jpg
            [postname] => sample.jpg
        )
)

结论

我看不到使用 HTTP PUT 上传文件的方法。 可以做到吗?

$image = fopen($file_path, "rb");

$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_PUT, 1);
curl_setopt($curl, CURLOPT_INFILE, $image);
curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file_path));

$result = curl_exec($curl);
curl_close($curl); 

可以使用以下代码完成:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM