Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PHP cURL to send images with the correct Content-Type?

Tags:

php

curl

Objective:

I want to send multiple images using multipart/form-data. Below is a snippet of my code.

Problem:

On one PC, the multipart attachment is sent by the correct MIME header Content-Type: image/jpeg, but on another PC, the MIME header is Content-Type: application/octet.

Question:

How can I force cURL to set the correct Content-Type header for the MIME content?

$ch = curl_init();

$params = array('name' => '@D:\globe.jpg');  

$base_url = "https://example.com"."?".varEncode($test_data);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_URL,$base_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

$result = curl_exec($ch);
like image 218
kjloh Avatar asked Nov 02 '10 04:11

kjloh


1 Answers

Use the CURLOPT_HTTPHEADER option:

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: image/jpeg"));

So specify Content-Type headers specifically for file uploads, use:

$params = array('name'=>'@D:\globe.jpg;type=image/jpeg');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
like image 149
netcoder Avatar answered Oct 07 '22 16:10

netcoder