Upload images to Imgur with Curl PHP

imgur api
imgur api upload image
imgur api example
imgur register application
imgur api python
imgur api javascript
imgur api get random image
how to upload image using rest api in php
<form action="php.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="img[]" type="file" multiple="multiple" /><br />
  <input type="submit" value="Send files" />
</form>
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
foreach ($_FILES['img']['tmp_name'] as $index => $tmpName) {
    if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
    {
        $handle = fopen($tmpName, "r");
        $data = fread($handle, filesize($tmpName));
        $client_id = "d5f419ef9aedf16";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
        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_POSTFIELDS, array('image' => base64_encode($data)));
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w'));

        $reply = curl_exec($ch);
        $info = curl_getinfo($ch);
        var_dump($info);
        if(curl_errno($ch))
            echo 'Curl error: '.curl_error($ch);
        curl_close($ch);
        $reply = json_decode($reply);
        printf('<img height="180" src="%s" >', $reply->data->link);
    }
}
?>

I made this page, works perfectly on localhost but when I run it from my server it does not work, problem is I have no output at all, not even the curl_getinfo or errors. Dont know how to debug this since I can't get any info out of it.

Thank you hans for the suggestions, you were right, it was not mandatory to use base64, not in V3 API, it was on the previous versions, not anymore. Now it's much faster. This is my final code

if(!empty($_FILES['img']['tmp_name'])){
    foreach ($_FILES['img']['tmp_name'] as $index => $tmpName) {
        if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
        {
            if ($handle = fopen($tmpName, "rb")) {
                $data = stream_get_contents($handle, filesize($tmpName));
                $client_id = "d5f619ef9aedf16";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
                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_POSTFIELDS, array('image' => $data));
                curl_setopt($ch, CURLOPT_VERBOSE, true);
                $reply = curl_exec($ch);
                if(curl_errno($ch))
                    echo 'Curl error: '.curl_error($ch);
                curl_close($ch);
                $reply = json_decode($reply);
                $screens .= $reply->data->link . " ";
                fclose($handle);
            }
        }
    }
}

The reason why it was not uploading them images was upload_max_filesize and max_post_size, I've increased them and I had no problems.

A php script to upload images to Imgur anonymously using Imguy , $url = 'https://api.imgur.com/3/image.json'; curl_setopt_array($curl, array( curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);. Imgur provides developers to upload images anonymously using their app. For this you only need to signup for Imgur and get an Application Client ID. In this post I’m going to tell you the step by step process of uploading images using Imgur API in PHP. This is pretty easy. You only have to send a POST request to a file on their site.

you do several things wrong.

this code: foreach ($_FILES['img']['tmp_name'] as $index => $tmpName) { will be executed even on GET requests, which contains no files, thus $_FILES['img'] does not exist, and you get an Undefined index: img error. furthermore, on GET requests, this undefined index bug returns NULL to foreach, and when you tell foreach() to loop a NULL, it gives you this error: Invalid argument supplied for foreach(). the fact that you haven't already caught up on this, proves that you're not checking the php error logs. this is the first thing you should do, when debugging a malfunctioning php script. - to fix both of these, wrap the foreach in if(!empty($_FILES['img']['tmp_name']){} - next, find your PHP error logs, and read those error reports. (usually you can find it in phpinfo() under error_log - or in case its emptystring, its your web servers' error log, eg for nginx with an empty php error_log php setting, its in nginx's error log (like /var/log/nginx/error.log )

next issue, $handle = fopen($tmpName, "r"); this will corrupt binary data (like images) on some systems (famously, windows), change it to rb for safely reading binary data (and image formats are binary)

next issue, you believe that fread() reads as many bytes as you request it to read, that is incorrect. fread will read UP TO as many bytes as requested, but can stop for many reasons before it has read the requested number of bytes. you'll either have to loop calling fread until it has read all the bytes, or better yet, use stream_get_contents, which will essentially do that fread() loop for you.

next issue, this line curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); is completely unnecessary, PHP's STDERR is libcurl's default STDERR anyway.

next issue, you don't fclose() $handle. this is ok for short running scripts (becuase the OS fclose() it for you when the script finishes), but the bigger your code grows, the longer the resource leak will be there, its a good programming habit to always close it, so do that.

next issue, i can't believe imgur actually wants a base64 encoded copy of the image, that is such a cpu & bandwidth & ram waste... the POST encoding they're using, multipart/form-data is fully binary safe, so there's no reason to base64 encode it... are you sure they want it base64 encoded? you AND them can save about 33% bandwidth by NOT using base64 encoding here.

given all the things you are doing wrong with the file operations, it'd be better to use the file_get_contents function - it reads the entire file, it opens the file in binary read mode (as opposed to your code, where you open it in TEXT mode, potentially corrupting the image as you read it), and it reads the entire file, not just the chunk of it that the first fread() call will read (which, if you're lucky, is the entire file, but if you're not lucky, is just the first chunk of it), and it does fclose() for you (which you forget to do)

Imgur API, This also works if you'd like to upload images anonymously (without the image curl --location --request POST 'https://api.imgur.com/oauth2/token' \ --form� However I need to upload multiple images at once. On the client side, the user will have multiple <input type="file" /> fields. I'm completely stuck now with figuring out where and how I will need to modify this code in order to handle multiple image upload when they come through to the server in the form of an array.

Why dont you use imgur php sdk and simple implement it with below code:

require_once APPPATH."/third_party/imgur/vendor/autoload.php";


    $pathToFile = '../path/to/file.jpg';
    $imageData = [
        'image' => $pathToFile,
        'type'  => 'file',
    ];

    $client->api('image')->upload($imageData);

Uploading Images Using Imgur API in PHP, Is PHP cURL extension installed ? If the above didn't fix your problem, add this code just after setting the $curl variable in the code :. If you want to upload images to an external server which is uploaded to your site by a client, you are at the right tutorial. For this submission we will use 2 files : form.php – The Page Where we will show the client the form. This file also sends the uploaded data to the external server.

Super easy upload image to Imgur using Laravel and Guzzle, I'm currently working on an Imgur API which should upload images, gifs Sadly none of them seem to give curl the string it wants if I use a video; it works just fine with images and <?php // the posted stuff from my form $title� For images only: Set to webpurify or aws_rek to automatically moderate the uploaded image using the WebPurify Image Moderation add-on or the Amazon Rekognition AI Moderation add-on respectively. notification_url: String: An HTTP or HTTPS URL to receive the upload response (a webhook) when the upload or any requested asynchronous action is

Upload an Video with Imgur Api : PHPhelp, HTML form to upload image. curl_setopt() Table of Contents. post I'm going to tell you the step by step process of uploading images using Imgur API in PHP… imgurUpload is a lightweight solution for cURL-based anonymous uploads to imgur's image API endpoint. The goal of this PHP class is to provide an easy set of methods to allow users to upload images, and receive a imgur URL in a properly formatted JSON response. This class can be used wth an ajax post call or a regular PHP $_POST script. Methods

upload image using curl php, I am planning to upload images to imgur anonymously using its api, i registered my curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/upload.json');� Since the API docs told me that I need to post it as a Binaryfile I tried using fopen(), fread(), file_get_contents()and countless more. Sadly none of them seem to give curl the string it wants if I use a video; it works just fine with images and gifs (which are now being sent as binary - before I used base64encode before passing it to curl).

Comments
  • check $data if it empty
  • Looks like if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) ) is not met, that's why. On local is met but on the server is not.
  • So i tried to var_dump($_FILES); , if I try 3 or more images var_dump output is empty, for 1 or 2 images I get output: array(1) { ["img"]=> array(5) { ["name"]=> array(2) { [0]=> string(5) "1.png" [1]=> string(5) "2.png" } ["type"]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } ["tmp_name"]=> array(2) { [0]=> string(0) "" [1]=> string(0) "" } ["error"]=> array(2) { [0]=> int(1) [1]=> int(1) } ["size"]=> array(2) { [0]=> int(0) [1]=> int(0) } } }
  • there should be permission problem that php cannot write to /tmp dir