Php curl upload file multipart/form-data

I am trying to post an image with cURL in PHP using multipart/form-data header since API that I am sending to is expecting image to be sent as multi-part form.

I don't have problems talking to the API with other requests; only posting an image is an issue.

I am using this form on client side:

and this is the server I am posting to (here I am trying to post this data forward to an API):

$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $imgRawData); // <-- raw data here hm?
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); <-- using this as I wanted to check if HTTPHEADER is set
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data')); <-- setting content-type header?
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

// i get response from the server
$response = curl_exec( $ch );

// with this I can check what kind of content type the last request had?
$requestContentType = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
echo "
request Content Type was:".$requestContentType."
"; curl_close($ch); echo "
SERVER POST IMAGE RESPONSE:
"; echo $response;

With the code below I am able to see my request headers:

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

var_dump(curl_getinfo($ch));

The content-type in request-headers is shown correctly now. But it seems the image is not send correctly as API would expect. Unfortunately I don't have access to the API...

Any help appreciated, thank you

We want to upload file to a server with POST HTTP request. We will use curl functions.


// data fields for POST request
$fields = array("f1"=>"value1", "another_field2"=>"anothervalue");

// files to upload
$filenames = array("/tmp/1.jpg", "/tmp/2.png");

$files = array();
foreach ($filenames as $f){
   $files[$f] = file_get_contents($f);
}

// URL to upload to
$url = "http://site.com/upload";


// curl

$curl = curl_init();

$url_data = http_build_query($data);

$boundary = uniqid();
$delimiter = '-------------' . $boundary;

$post_data = build_data_files($boundary, $fields, $files);


curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => $post_data,
  CURLOPT_HTTPHEADER => array(
    //"Authorization: Bearer $TOKEN",
    "Content-Type: multipart/form-data; boundary=" . $delimiter,
    "Content-Length: " . strlen($post_data)

  ),

  
));


//
$response = curl_exec($curl);

$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

var_dump($response);
$err = curl_error($curl);

echo "error";
var_dump($err);
curl_close($curl);




function build_data_files($boundary, $fields, $files){
    $data = '';
    $eol = "\r\n";

    $delimiter = '-------------' . $boundary;

    foreach ($fields as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
            . $content . $eol;
    }


    foreach ($files as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
            //. 'Content-Type: image/png'.$eol
            . 'Content-Transfer-Encoding: binary'.$eol
            ;

        $data .= $eol;
        $data .= $content . $eol;
    }
    $data .= "--" . $delimiter . "--".$eol;


    return $data;
}


Some web services ask to upload or Post some files on server. In this post we will explain you How to send files via Form Post. We are using cURl to send files on server.

cURL is very powerful library, you can Get or Post data using cURL method.

PHP cURL code to Send File

First create a simple HTML form to upload a file.

Make sure that form use ‘multipart/form-data‘ enctype value. This will post data in URL encrypted form.

<form enctype="multipart/form-data"action="receiver.php"method="POST">

Please chooseafile:<input name="uploaded"type="file" /><br/>

<input type="submit"name="submit"value="Upload"/>

</form>

Now create a receiver.php file to handle this form post request.

In this file cURL send file to any web server. Check it out below code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

$target="/home/jobsjqvi/public_html/codefixup.com/codefile/";

$target=$target.basename($_FILES['uploaded']['name']);

$headers =array(

'Authorization: Bearer Token Value',

'Content-type: multipart/form-data'

);

$url="https://example.com/api/v1/import/uploadfile";

$csv_file=new CURLFile($target,'text/csv');

$post_data=array(

      "importfile"=>$csv_file

    );

$curl= curl_init();

curl_setopt($curl,CURLOPT_VERBOSE,true);

curl_setopt($curl,CURLOPT_HEADER,false);

curl_setopt($curl, CURLOPT_POST,true);

curl_setopt($curl,CURLOPT_URL,$url);

curl_setopt($curl,CURLOPT_POSTFIELDS,$post_data);

curl_setopt($curl, CURLOPT_HTTPHEADER,$headers);

$response=curl_exec($curl);

$status=curl_getinfo($curl,CURLINFO_HTTP_CODE);

curl_close($curl);

?>

If you found that file is imported as empty or any other issue, must upload the file in target path.

Than try to upload file again using html form. This will work without any issue.

  • How to Convert HTML to PDF Document in PHP using fpdf
  • Visitor Counter in PHP for Website
  • Multiple Star Rating Feature on Single Page in PHP, MySQL and Ajax

About Harish

I am professional web developer and blogger. Use this blog to share own api and other web development experience with you. I do accept paid work. Write to me at -

View all posts by Harish

How do I pass a multipart file in Curl?

With curl, you add each separate multipart with one -F (or --form ) flag and you then continue and add one -F for every input field in the form that you want to send. The above small example form has two parts, one named 'person' that is a plain text field and one named 'secret' that is a file.

How to pass form data in Curl PHP?

To post a web form with Curl, you need to use the -d command line option and pass the form data as key/value pairs. By default, Curl sends an HTTP POST request and posts the provided form data with the application/x-www-form-urlencoded content type.

How do I post form data using Curl?

To post form data with Curl, you can use one of two command-line parameters: -F (--form) or -d (--data). The -F command-line parameter sends form data with the multipart/form-data content type, and the -d command-line parameter sends form data with the application/x-www-form-urlencoded content type.

What is Curlopt_postfields?

CURLOPT_POSTFIELDS. The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'.