1

I want to upload some pictures with the imgur-API to imgur, but I am always getting an Error 400 Bad Request. Whats the issue?

<?php
if (isset($_POST['uploadprofileimg'])) {
    $image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
    $options = array('http'=>array(
            'method'=>"POST",
            'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
            "Content-Type: application/x-www-form-urlencoded",
            'content'=>$image
    ));
    $context = stream_context_create($options);
    $imgurURL = "https://api.imgur.com/3/image";
    $response = file_get_contents($imgurURL, false, $context);
}
?>

<h1>My Account</h1>
 <form action="upload-pb.php" method="post" enctype="multipart/form-data">
    Upload a profile image:
    <input type="file" name="profileimg">
    <input type="submit" name="uploadprofileimg" value="Upload Image">
</form>
Blue
  • 22,608
  • 7
  • 62
  • 92
Tobiw
  • 13
  • 3

1 Answers1

0

Looking at the endpoint for /image here, it needs a parameter of image. You're passing it in as content, and not properly encoded as image. Looking here, I borrowed how to properly upload content using stream_context_create/file_get_contents:

<?php
 if (isset($_POST['uploadprofileimg'])) {
    $image = base64_encode(file_get_contents($_FILES['profileimg']['tmp_name']));
    $postdata = http_build_query(
        array(
            'image' => $image,
        )
    );
    $options = array('http'=>array(
            'method'=>"POST",
            'header'=>"Authorization: Bearer *MY_ACCESS_TOKEN*\n".
            "Content-Type: application/x-www-form-urlencoded",
            'content' => $postdata
    ));
    $context = stream_context_create($options);
    $imgurURL = "https://api.imgur.com/3/image";
    $response = file_get_contents($imgurURL, false, $context);
Blue
  • 22,608
  • 7
  • 62
  • 92
  • Also, consider skipping `base64_encode` all together. It will make uploads smaller, and should work uploading the binary file to imgur. – Blue Feb 11 '19 at 23:38