I have been very frustrated in my attempt to send an image to an API using Curl. The image is coming from an html form from the clients end. When the form is submitted, I check to make sure the file is an image and the image is moved to an uploads folder as such:
$location = "ImageUploads/";
if(isset($_FILES["Image"]["tmp_name"]))
{
$checkImage = getimagesize($_FILES["Image"]["tmp_name"]);
if($checkImage !== false){
$Image = $_FILES['Image']['tmp_name'];
$ImageContent = addslashes(file_get_contents($Image));
$ImagePosted =true;
$ImageRealName = $_FILES['Image']['name'];
if(move_uploaded_file($Image, $location.$ImageRealName))
{
echo 'File Uploaded';
}
}
else{
echo 'Image not submitted';
}
After I move the image to an uploads folder, I initiate the curl Post as such:
$baseURL ="https://apithatIamusing.com/api/";
$curl = curl_init($baseURL);
$myImage = new CURLFile($location.$_FILES['Image']['name'],$_FILES['Image']['type'],$_FILES['Image']['name']);
After this, I create a curl_post_data array to include the rest of the api data requirements:
$curl_post_data = array(
'public_key' => $publicKey,
'private_key' => $privateKey,
'order_type' => 'Image',
'origin_id' => '11111111',
'name' => $FirstName,
'surname' => $LastName,
'photo' => $myImage);
I then set all of the Curtopts that I will be using:
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
I then execute and attempt to decode the json response:
$imageResult= curl_exec($curl);
if($imageResult ===false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
$imageJson = json_decode($imageResult, true);
curl_close($curl);
$imageSuccess = $imageJson["success"];
$imageMessage = $imageJson["message"];
$imageSuccess = $imageJson["result"];
echo '<p>imageSuccess:'.$imageSuccess.' </p>';
echo '<p>imageMessage: '.$imageMessage.' </p>';
echo '<p>imageSuccess: '.$imageSuccess.' </p>';
I believe that the issue could be with the $myImage that curl is creating, the api documentation asks for the 'photo' to include the following information:
filename="t1.png"
Content-Type: image/png
But, to my understanding, curlfile is including, the name, content-type and the post name. Any recommendations or other methods to make this api post call using php would be greatly appreciated.