转换 cURL 以在 php 函数中使用

Convert cURL to be used in php function

目前我正在 box 平台上工作,并尝试将文件上传到 box 服务器。 Box 使用 cURL 上传文件,我正在尝试从 php 发送 cURl 请求。到目前为止,我已经将大部分 cURL commads 转换为 php 行话,但我无法弄清楚如何传递要上传的文件的属性(名称、路径、包含文件夹)。

这是 cURL

curl https://upload.box.com/api/2.0/files/content -H "Authorization: Bearer APP_USER_TOKEN" -X POST -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=@Jon_Snow.jpeg

这里是不完整的 cURL 命令的 php 版本。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://upload.box.com/api/2.0/files/content");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Authorization: Bearer ".json_decode($accessToken, true )['access_token'];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

如何执行 cURL 命令的最后一部分

-F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' -F file=@Jon_Snow.jpeg

编辑:'possible duplicate' 的建议不准确,我想问一种方法,以 -F attributes='{"name":"Jon_Snow.jpeg", "parent":{"id":"0"}}' 的形式向上传的文件添加属性,我不明白建议的答案有何相关性

试试这个:art about sending files via post and curlib

-F 选项意味着您要发送一个包含名称和内容的 post 字段。本例中的内容来自文件,因为您使用的是@前缀

找到答案,我需要 json_encode 属性数组,然后使用 new \CURLFile() 函数创建文件句柄,它不适用于 realpath()

$attributes = array('name'=>$fileName,'parent'=>array('id'=>$folderId));
$file = new \CURLFile($filePath);
$fields = array('attributes' => json_encode($attributes), 'file' => $file);
$headers = array("Authorization: Bearer ".$accessToken);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($ch);