[英]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.