Home >Backend Development >PHP Tutorial >How Can I Successfully Post Images as Multipart/Form-Data Using cURL in PHP?
Posting Images as Multipart/Form-Data in cURL
Issue:
Users encounter difficulties posting images using cURL in PHP with multipart/form-data headers, despite being able to communicate effectively for other API requests. Current efforts have failed to resolve the image posting challenge.
Proposed Solution:
As of PHP versions 5.6 and 7, using $filePath in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD set is deprecated. In PHP 7, $filePath is entirely removed. To address this, implement a CurlFile object.
Implementation:
$fields = [ 'name' => new \CurlFile($filePath, 'image/png', 'filename.png') ]; curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);
This approach allows for posting images as multipart/form-data, adhering to the RFC specification.
The above is the detailed content of How Can I Successfully Post Images as Multipart/Form-Data Using cURL in PHP?. For more information, please follow other related articles on the PHP Chinese website!