Adding a file

Hi all.

First question here.
Im having trouble uploading a file. I’ve used the example code given by pipedrive but it doesn’t seem to work for me.

Would you be able to tell me what’s wrong in the code below? Am I missing something?

// Location of the file and person ID of the person to whom you assign the file
$data = array(
    'file' => curl_file_create('./testfile.docx'),
    'person_id' => 16
);


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.pipedrive.com/v1/files?api_token=MyAPIToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


echo 'Sending request...' . PHP_EOL;
$output = curl_exec($ch);
echo "<pre>";
print_r(curl_getinfo($ch));
echo "</pre>";
// Create an array from the data that is sent back from the API
// As the original content from server is in JSON format, you need to convert it to PHP array
$result = json_decode($output, true);



var_dump($result);
var_dump(curl_error($ch));
curl_close($ch);



// Check if the data returned in the result is not empty
if (empty($result['data'])) {
    exit('Adding failed' . PHP_EOL);
}

// Check if file ID came back, if it did, print out success message
if (!empty($result['data']['id'])) {
    echo 'File added successfully! ' . PHP_EOL;
}

echo "<br />Headers: ";
var_dump($headers);

echo "<br />Body: ";
var_dump($body);

Current output:

Hey @RIchard

Thanks for sharing the snippet. I made some modifications to the snippet to print out the headers as well. Can you try running this and let me know?
https://replit.com/@HemchanderSunda/adding-file-pipedrive-api?lite=true

With the code used below:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.pipedrive.com/v1/files?api_token=$apiToken");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


echo 'Sending request...' . PHP_EOL;
$output = curl_exec($ch);
//Print output with headers
var_dump($output);

// Print error
var_dump(curl_error($ch));
curl_close($ch);

// Check if the data returned in the result is not empty
if (empty($result['data'])) {
    exit('Adding failed' . PHP_EOL);
}

// Check if file ID came back, if it did, print out success message
if (!empty($result['data']['id'])) {
    echo 'File added successfully! ' . PHP_EOL;
}

I got an empty result.

Output is:
Sending request… bool(false) string(0) “” Adding failed