Table of contents

multipart/form-data post using cURL php

PHP cURL May 16, 2020 Viewed 11K Comments 0

With multipart/form-data post in cURL, we can submit not only json and arrays, but also files. When sending files, we need to pay attention to the php version. Below PHP 5.5, we can directly add the @ symbol in front of the file path. For those >= PHP 5.5, we need to use the CURLFile class, or curl_file_create.

Example

Note that curl_setopt ($ curl, CURLOPT_POST, true) must be placed before curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ data). Otherwise, an error will be sent.

function post($url, $data, $headers)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true, // return the transfer as a string of the return value
        CURLOPT_TIMEOUT => 0,   // The maximum number of seconds to allow cURL functions to execute.
        CURLOPT_POST => true,   // This line must place before CURLOPT_POSTFIELDS
        CURLOPT_POSTFIELDS => $data // The full data to post
    ));
    // Set Header
    if (!empty($headers)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $errno = curl_errno($curl);
    if ($errno) {
        return false;
    }
    curl_close($curl);
    return $response;
}

Use it

The Content-Type of request header will be automatically set to multipart/form-data.

$data = [
    "name" => "test",
    "password" => "mypasswd",
];
$file = "/Users/apple/Downloads/201228bli.bmp";
// php 5.5+ should use curl_file_create method
if (function_exists('curl_file_create')) {
    $data['avatar'] = curl_file_create($file);
} else {
    $data['avatar'] = '@' . $file;
}
$headers = ["User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"];
echo post("http://localhost/response.php", $data, $headers);

response.php

print_r($_REQUEST);
$contentType = $_SERVER["CONTENT_TYPE"];
print_r($contentType);

Output

Array
(
    [name] => test
    [password] => mypasswd
)
multipart/form-data; boundary=------------------------37d33deee2fc7597
Updated May 16, 2020