E
E
Eugene2021-09-04 16:24:21
PHP
Eugene, 2021-09-04 16:24:21

How to send a POST image in multipart/form-data format?

I'm trying to send a picture via the VK API, I get the server address, I send a request, it seems like everything works, but an empty "photo" field is returned in response. As if the picture was not sent. What am I doing wrong?

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

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

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

    return $data;
}

$VKimgLoadServer = json_decode(file_get_contents($VKimgLoad));
if(isset($VKimgLoadServer -> error))
    print_r($VKimgLoadServer);

else{
    $files = array(
        "photo" => file_get_contents("./img/post/2017-08/201708131447301997.png"),
    );

    $curl = curl_init();
    $boundary = uniqid();
    $delimiter = '-------------' . $boundary;
    $post_data = build_data_files($boundary, $files);
    
    curl_setopt_array($curl, array(
        CURLOPT_URL => $VKimgLoadServer -> response -> upload_url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $post_data,
        CURLOPT_HTTPHEADER => array(
            "Content-Type: multipart/form-data; boundary=" . $delimiter,
            "Content-Length: " . strlen($post_data)
        )
    ));
  
    $response = curl_exec($curl);
    $info = curl_getinfo($curl);
    curl_close($curl);
    echo $response;

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2021-09-04
@melkij

You use curl to make the request anyway. Ask curl to generate a valid request body.
https://www.php.net/manual/en/curlfile.construct.php

A
Anton Shamanov, 2021-09-04
@SilenceOfWinter

if you want without extra brainwashing, then just specify the files with links, they are on your http server ..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question