PHP for sending multipart/form-data request with cURL


PHP for Sending Multipart/Form-Data Request with cURL

Code Solution

<?php

$curl = curl_init();

$data = [
    'name' => 'John Doe',
    'file' => curl_file_create('image.jpg')
];

curl_setopt_array($curl, [
    CURLOPT_URL => 'http://example.com/upload',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data
]);

$response = curl_exec($curl);
curl_close($curl);

?>

Explanation

This PHP code uses the cURL library to send a multipart/form-data request to a remote API. The code is broken down into the following steps:

  1. Initialize a cURL handle using curl_init().

  2. Create an array containing the data to be sent in the request. The data array should have key-value pairs, where the keys are the form field names and the values are the data to be sent.

  3. For file uploads, use curl_file_create() to create a curl file object. This will ensure that the file is sent as a multipart/form-data part.

  4. Set the cURL options using curl_setopt_array():

    • CURLOPT_URL: The URL of the remote API.
    • CURLOPT_RETURNTRANSFER: Set to true to return the response as a string.
    • CURLOPT_POST: Set to true to send the request using the POST method.
    • CURLOPT_POSTFIELDS: Set to the data array containing the form fields and file uploads.
  5. Execute the cURL request using curl_exec().

  6. Close the cURL handle using curl_close().

Implementation

To implement this code, you can follow these steps:

  1. Ensure that the cURL library is installed and enabled on your system.

  2. Create a PHP script and paste the code into it.

  3. Replace the placeholder values in the $data array with your own form field names and data.

  4. Set the CURLOPT_URL option to the URL of the remote API that you want to send the request to.

  5. Run the PHP script to send the multipart/form-data request.

  6. Check the response from the remote API to see if the request was successful.