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>
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;
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!