phpcurlbox-apiboxapiv2

Upload file with Box.com PHP API


I am trying to upload a file to box.com using Box API. According to the docs, the curl request has to look like this:

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

Here's what I did:

$token = "......";
$url = https://upload.box.com/api/2.0/files/content;
$file_upload;

foreach ($_FILES['file']['name'] as $position => $file) { 
    $file_upload = $_FILES['file']['tmp_name'][$position];
}
$json  = json_encode(array('name' => $file ,array('parent' => array('id' => 0))));
$attrs = array('attributes' => $json,'file'=>'@'.$file_upload);

$this->post($url,($attrs));

// Post function
function post($url,$fields){
    try {       
        $ch = curl_init();          
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization: Bearer '.$this->token
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);          
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        self::$response = curl_exec($ch);
        curl_close($ch);

    } catch (Exception $e) {
        self::$response = $e->getMessage();
    }       

    return  self::$response;
}

But it doesn't work. Is there anything wrong in curl part?


Solution

  • Using CurlFile instead of '@path' fixes the issue!