Search code examples
phpimgur

imgur commerce - how upload image to album?


For upload image in album on imgur.com we are use it information and it code:

$image = file_get_contents($_FILES['upload']['tmp_name']);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://imgur-apiv3.p.mashape.com/3/image');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Authorization: Client-ID ' . $client_id ));
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-Mashape-Key:  ' . $xmash ));
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type:  application/x-www-form-urlencoded' ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'image' => base64_encode($image) ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'album' => $album_id ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'type' => 'base64' ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'name' => 'test_name' ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'title' => 'test title' ));
curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'description' => 'blablabla' ));
$result= curl_exec($ch);
var_dump($result);
curl_close($ch);

but in result we are get error Invalid image type.

Tell me please why we are get it error and how upload image in album?

P.S.: we are test commerce accout.


Solution

  • Ensure your image is structured correctly first before sending the base64..

    $baseContent = "";
    
    if (isset($_FILES['upload']['tmp_name'])) {
            $imgbinary = fread(fopen($_FILES['upload']['tmp_name'], "r"), filesize($_FILES['upload']['tmp_name']));
            $baseContent = 'data:image/png;base64,' . base64_encode($imgbinary);
        }
    

    This will set the $baseContent var to the base64.. Then just pass through to your request :

    curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'image' => $baseContent ));
    

    Looks like it's not formatting correctly. I havent tested this fully but it should ensure you have the correct base64.