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:
-
Initialize a cURL handle using
curl_init(). -
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.
-
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. -
Set the cURL options using
curl_setopt_array():CURLOPT_URL: The URL of the remote API.CURLOPT_RETURNTRANSFER: Set totrueto return the response as a string.CURLOPT_POST: Set totrueto send the request using the POST method.CURLOPT_POSTFIELDS: Set to the data array containing the form fields and file uploads.
-
Execute the cURL request using
curl_exec(). -
Close the cURL handle using
curl_close().
Implementation
To implement this code, you can follow these steps:
-
Ensure that the cURL library is installed and enabled on your system.
-
Create a PHP script and paste the code into it.
-
Replace the placeholder values in the
$dataarray with your own form field names and data. -
Set the
CURLOPT_URLoption to the URL of the remote API that you want to send the request to. -
Run the PHP script to send the multipart/form-data request.
-
Check the response from the remote API to see if the request was successful.