Search code examples
phpimageformsapimultipart

PHP Converting an Image to add Multipart Form Data


I am having some difficulty with an API. It has requested that I create a Multipart Form Data image

POST https://api.working.com/v1/detail/detail.example.id1/27f145d2-5713-4a8d-af64-b269f95ade3b/images/thumbnail/normal

------------------------------330184f75e21
Content-Disposition: form-data; name="image"; filename="icon.png"
Content-Type: application/octet-stream

.PNG
imagedata
Response

I am trying to find some example PHP script that will convert an image into this format

The image file must have the name image in the multipart form data

I am racking my brain and combing the internet to find something that works for me.

Does anyone have a snippet they can share please to help?

Thanks

Rob


Solution

  • Here's a basic curl example showing how to do it:

    $url = 'https://api.working.com/v1/detail/detail.example.id1/27f145d2-5713-4a8d-af64-b269f95ade3b/images/thumbnail/normal';
    
    $data = array(
        'image' => new CURLFile(
            '/path/to/icon.png', 
            'application/octet-string',
            'icon.png'
         ),
        'some_other_field' => 'abc',
    );
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    $response = curl_exec($ch);
    
    // do something with response
    
    // to debug, try var_dump(curl_getinfo($ch)); and var_dump(curl_error($ch));
    
    $ch = curl_init($url);
    

    Check out the CURLFile class for more info on file uploads, and curl_setopt() for more request options.