将Curl Command转换为PHP以进行文件上载

时间:2015-06-22 22:37:55

标签: php curl

嘿我需要帮助将此命令转换为PHP代码。

该命令工作正常,但是当我从PHP执行该命令时,我得到400错误代码。不知道我在这里错过了什么:

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

这是我提出的PHP代码:

$url = 'https://upload.box.com/api/2.0/files/content';
$headers = array('Authorization: Bearer FK7KyL3LRtjlLdrvtrrDIxqGIoHWh7Kj');
$fields = array('attributes'=>'{"name":"test.test", "parent":{"id":"0"}}', 'file'=>'@test.test');

echo $file_path . "<br>";
print_r($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($ch);
$r_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload results</title>
</head>
<body>
    <p>Code: <?=$r_code?></p>
    <p>Raw Result: <?=$result?></p>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情并解决了这个问题。 不确切知道它是什么,但这是工作代码:

$url= 'https://upload.box.com/api/2.0/files/content';
$accesstoken= ACCESS_TOKEN;
$filename= realpath('1.gif');

$attributes = array('name'=>'2.gif','parent'=>array('id'=>"0"));

$params = array('attributes' => json_encode($attributes), 'file' => "@".realpath($filename));
$headers = array("Authorization: Bearer ".$accesstoken);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CERTINFO, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_VERBOSE, true);

$data = curl_exec($ch);
print_r($headers);
print_r(curl_getinfo($ch));
print_r(curl_error($ch));
curl_close($ch);

print_r($data);