How to use PHP/Curl to post a file to restful api?

4.3k views Asked by At

I'm trying to post avatar images from my website to pipedrive using PHP/Curl. The docs require a multipart/form-data encoding. I can't seem to get the actual file to post. I've tried several ways to send the file from various how-to's but every time pipedrive returns "no file attached". I've pasted my current attempt below, any ideas? Or perhaps just point me to an example that would work?

$ch = curl_init();
$timeout = 10;
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_INFILESIZE, $params['filesize']);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER,
   array('Content-Type:multipart/form-data')
);
$data = curl_exec($ch);

$params = array(
    'id' => $PDid,
    'file' => plugin_dir_path( dirname( __FILE__ )).'tmp/'.$filename,
    'filesize' => filesize(plugin_dir_path( dirname( __FILE__ )).'tmp/'.$filename)
);
1

There are 1 answers

1
mkasberg On BEST ANSWER
  1. You need to set the $params variable at the top of your script before you use it. It does you no good at the bottom.

  2. Read the documentation for CURLFile and follow the example there.

Specifically, you should set the relevant file options like this:

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$params = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

In the code you posted, it looks like you are missing CURLOPT_POST. And Your CURLOPT_POSTFIELDS isn't working because as I said $params has not been initialized yet.