Search This Blog

Thursday, April 26, 2018

PHP curl to upload a FILE with POST data



$ch = curl_init();

$fname = 'd:/temp/xxx.jpg';   
//windows
$cfile = new CURLFile(realpath($fname));
//linux
//$cfile = new CURLFile(realpath($fname), 'application/octet-stream', 'filename.pdf');

$data = array('param' => 'value', 
'param2' => 'value2',
'param3' => '{"jsonkey1":"jsonvalue1","jsonkey2":"jsonvalue2"}',
'file' => $cfile
);

curl_setopt($ch, CURLOPT_URL, 'https://api-url');
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('cache-control: no-cache','Content-Type: multipart/form-data'));
//curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response  = curl_exec($ch);

$err = curl_error($ch);

//echo "INfo : ".implode(',',curl_getinfo($ch));

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err;
} else {
  echo "Success : ".$response;
}

?>

Post a Comment

Hit Counter


View My Stats