file - PHP Post Request with CURL - image + array


I'm trying to post a multipart request to an API that contains both an image and an array that has details about that image. This request works via Postman but implementing it using CURL in PHP is proving difficult.

The headers are pretty basic - they just contain an $auth_token that is retrieved previously from other api calls.

$headers = array('Content-Type: multipart/form-data', 'Authorization-token: ' . $auth_token));

The actual body of the form data is as follows - a CurlFile is instantiated as follows and an array with information about the file

$fields = array(
    "data" => new CurlFile('C://images/15.jpg', 'image/jpg', '15.jpg'),
    "entityFile" => array(
        "fileTypeID"=> "server generated id",
        "fileSize"=> 23453,
        "entityID"=> "another server generated id",
        "fileDateUtc"=> "2018-02-26T00:00:00",
        "fileName"=> "15",
        "fileExtension"=> "jpg"

Finally I set options for the data to be sent

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);

I have also tried attaching the image as a base64 encoded string but the image on the server is not changed.

My question is whether there is anything apparently wrong with my $fields array that might be causing it to fail? I suspect that there may be a problem with the actual file but it is hard to determine as the actual error returned is...

The requested URL returned error: 400 Bad Request

Thank you

People are also looking for solutions to the problem: php - Why Won't My Register/Login Forms Check/Update Database


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.