PHP cURL:如何将正文设置为二进制数据?

2022-08-31 00:27:25

我正在使用一个 API,该 API 希望我发送一个 POST,其中包含文件中的二进制数据作为请求的正文。如何使用 PHP cURL 完成此操作?

与我试图实现的目标等效的命令行是:

curl --request POST --data-binary "@myimage.jpg" https://myapiurl

答案 1

您可以将身体设置在 .CURLOPT_POSTFIELDS

例:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

取自此处

当然,设置自己的标头类型,并且只对正文执行操作。file_get_contents('/path/to/file')


答案 2

这可以通过 CURLFile 实例完成:

$uploadFilePath = __DIR__ . '/resource/file.txt';

if (!file_exists($uploadFilePath)) {
    throw new Exception('File not found: ' . $uploadFilePath);
}

$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';

$uploadFile = new CURLFile(
    $uploadFilePath,
    $uploadFileMimeType,
    $uploadFilePostKey
);

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify array of form fields
     */
    CURLOPT_POSTFIELDS => [
        $uploadFilePostKey => $uploadFile,
    ],
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

请参见 - https://github.com/andriichuk/php-curl-cookbook#upload-file


推荐