How to Build a Dynamic Imgur Upload App Using jQuery & PHP

by on 29th August 2013 with No Comments

preview tutorial imgur mirror upload jquery php

Many new online web services are providing backend APIs for developers. These allow anyone to connect into a web app and pull out specific information (or push or change bits of data). Today we’re specifically looking at the API for Imgur.

In this tutorial I want to demonstrate how we can remotely mirror an image found elsewhere online and auto-upload to Imgur. It’s possible to create a form handling user-uploaded images as well. But I wanted to keep the demo clean without needing to move user content onto the server. This process is very simple once you understand how APIs work. Take a peek at my live demo to see exactly what we will be making, then follow along!

Live DemoDownload Source Code

Webpage Layout

The actual page interface is very simple and it would be easy to customize for any other design. I have a small input box where the user should enter a direct URL linking to an image online. Instead of submitting a form onto another page we can handle the request via Ajax. The only dependency is a copy of the latest jQuery library.

<!doctype html>
<html lang="en-US">
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <title>Dynamic Imgur API Upload - Live Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designshack.net/favicon.ico">
  <link rel="icon" href="http://designshack.net/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="styles.css">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>

When we get a response back from the PHP script it should contain the new image URL. There is a long list of response parameters which are returned from Imgur that we could use. This includes the uploader username, image title, upload date, among other scraps of metadata. However for this demo I wanted to keep things simple and easy to follow along.

  <h1>API-Based Imgur Upload Webapp</h1>
  
  <input type="text" name="imageurl" id="imageurl" placeholder="Enter an image URL...">
  
  <a href="#" id="imgurupl">Upload to Imgur</a>
  
  <br><br>
  
  <div id="newimgurl">
    <p><strong>New Image URL: <a href="" id="newimgurllink"></a></strong></p>
  </div>

After clicking the Upload link it will push the image up onto Imgur. This will take a few seconds before we get the return data, which is then passed back into JavaScript. Targeting the anchor link #newimgurllink we can append the direct URL into the href value, plus adding the anchor text itself. It is a very basic solution for creating dynamic imgur links without a page refresh.

Delving into jQuery

There is only one large block of code which needs to be executed using jQuery. This happens once the user clicks on #imgurupl which calls the new Ajax request. I am using the hash symbol (#) for an href value because we cancel the original action using e.preventDefault().

$(function(){ 
  $('#imgurupl').on('click', function(e){
    e.preventDefault();
    var b64ajax = $.ajax({
      url: "upload.php",
      type: "POST",
      data: {url: $('#imageurl').val()},
      dataType: "html"
    });
    
    b64ajax.done(function(msg){
      $('#newimgurllink').html(msg).attr('href', msg);
    });
  }); 

});

The first thing we do is create a variable b64ajax to house the Ajax request. It will push the input field value out to a new page called upload.php which takes it as a POST variable. This is important because we need to access this URL value and return something back to the frontend.

This is applied onto the Ajax variable itself by running b64ajax.done(). It is a function which automatically runs after the callback finishes with an Ajax result. Assuming we get a string value passed back from PHP then we know an image was uploaded successfully, and so we append this link value into the HTML dynamically.

Imgur API in PHP

When searching around for Imgur v3 API demos I came across this wonderful script from Stack Overflow. It provides a locally-hosted image upload application tied directly to Imgur. Their code provides a nice baseline for what we are creating.

Now the first thing you need to do before even coding in PHP is to signup for an API key. You can register from this page only after you have signed into an account. So if you do not have an Imgur account you should register (it’s free). Once you create a new application this will automatically generate a new client and secret ID.

When accessing anonymous data all we need is the Client ID. Secret IDs are used to verify sessions when using OAuth to connect into user accounts. It can be very beneficial functionality, but not within the scope of this tutorial. There isn’t a whole lot of PHP to understand so I’ll break it down slowly.

$client_id = "YOURCLIENTIDHERE";

$image = $_POST['url'];

$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' => $image ));

Obviously $clientid should hold your new application ID. The URL variable passed through Ajax is set to a new variable, as well. cURL is a popular library of functions used to communicate with servers via a number of protocols. In this case we need to access the Imgur uploading endpoint which is defined as CURLOPT_URL.

One other really important idea to take away from these variables is the client ID setup. Within the Imgur API documentation you’ll notice there is a specific formatting we need to pass into the Ajax request headers. This looks like “Authorization: Client-ID YOURIDHERE” which can throw some people off. Just remember that you need the text Client-ID preceding the actual ID string.

$reply = curl_exec($ch);
curl_close($ch);

$reply = json_decode($reply);
$newimgurl = $reply->data->link;

echo $newimgurl;

exit();

These final lines of code simply run the HTTP request and then returns exactly what we need to pass into jQuery. curl_exec() and curl_close() should be fairly self-explanatory. Notice the execution function will return data from the server which is held in the variable $reply. Since we requested JSON data from the server we need to convert this into a PHP array using json_decode().

With this new response data array we just need to pull out the direct image URL. This can be accessed by $reply->data->link where $reply->data contains a subset of alternate variables. If you’re curious about this array you might run the code print_r($reply->data) to see what other pieces of information are returned. But finally to close the program we echo the response link URL and terminate with exit().

A lot of this code will become clearer once you are playing with it more. APIs are such a fun way to practice developing webapps because you get to learn by overcoming challenges along the way. Remember that because this demo is running through PHP it will only work properly when hosted on a local or remote web server.

Live DemoDownload Source Code

Final Thoughts

Imgur is one of the more confusing APIs that I have worked with because of the specific Client ID credentials system. Once you have everything setup it seems to work very reliably — feel free to download a copy of my source code and build out something similar in one of your own projects, or try to take the project a little further with direct file upload from the user’s computer!

Comments & Discussion

No discussion just yet... Get things started!

Leave a Comment

Subscribe
Membership
About the Author