I am wanting to send a file via http POST using PHP and cURL.
The form POST was working ok with basic fields besides the file being posted with 'application/json'. This needs to be multipart/form from what I understand.
Error I am getting is Notice: Array to string conversion on line curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
If anyone can help that would be great!
PHP
$orgID = (is_numeric($_POST['orgID']) ? (int)$_POST['orgID'] : 0);
$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);
if(isset($_FILES['file']['tmp_name'])){
$ch = curl_init();
$cfile = new CURLFILE($_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['name']);
$data = array();
$data["TITLE"] = "$noteTitle";
$data["BODY"] = "$noteBody";
$data["LINK_SUBJECT_ID"] = "$orgID";
$data["LINK_SUBJECT_TYPE"] = "Organisation";
$data['FILE_ATTACHMENTS']['FILE_NAME'] = $_FILES['file']['name'];
$data['FILE_ATTACHMENTS']['CONTENT_TYPE'] = $_FILES['file']['type'];
$data['FILE_ATTACHMENTS']['URL'] = $_FILES['file']['tmp_name'];
$localFile = $_FILES['file']['tmp_name'];
$fp = fopen($localFile, 'r');
$headers = array(
"authorization: Basic xxx",
"cache-control: no-cache",
"content-type: multipart/form-data",
"postman-token: xxx"
);
curl_setopt($ch, CURLOPT_URL, "https://api.insight.ly/v2.1/Notes");
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 86400); // 1 Day Timeout
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_NOPROGRESS,false);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localFile));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if ($response === true) {
$msg = 'File uploaded successfully.';
}
else {
$msg = curl_error($ch);
}
curl_close ($ch);
$return = array('msg' => $msg);
echo json_encode($return);
}
HTML
<form method="POST" action="formSend.php" enctype="multipart/form-data">
<input type="text" value="" name="orgID">
<input type="text" value="" name="noteTitle">
<input type="text" value="" name="noteBody">
<input name="file" type="file" id="file"/>
<input type="submit" value="Submit" name="btnUpload"/>
</form>