How to Send Raw Image Data via Multipart/Form-Data in cURL for PHP?

Susan Sarandon
Release: 2024-11-21 07:29:13
Original
914 people have browsed it

How to Send Raw Image Data via Multipart/Form-Data in cURL for PHP?

Sending Raw Image Data via Multipart/Form-Data in cURL for PHP

When interacting with an API that expects image data via multipart/form-data, posting the image correctly can be challenging. In PHP, this process involves setting multipart/form-data headers and handling raw image data.

Form Structure

On the client side, the HTML form can be created as shown:

<form action="http://myServerURL" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="Submit">
</form>
Copy after login

Server-Side Processing

On the server side, the PHP code to post the image data would be:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
$filePath = '/path/to/image.png';
$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieJar);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Get the response and check the content type
$response = curl_exec($ch);
$requestContentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
echo "<br>request Content Type was:".$requestContentType."<br>";

curl_close($ch);

echo "<br><b>SERVER POST IMAGE RESPONSE:</b><br>";
echo $response;
Copy after login

Using a CurlFile Object

In PHP versions before 5.6, using @$filePath without setting CURLOPT_SAFE_UPLOAD would work. However, in PHP 7 and above, it's necessary to use a CurlFile object to handle file uploads safely. This ensures that the raw image data is correctly transferred.

The above is the detailed content of How to Send Raw Image Data via Multipart/Form-Data in cURL for PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template