Uploading Images Using Imgur API in PHP

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.

Uploading Images Using Imgur API in PHP

Create Application & Get Client ID

You need to create an app to get the Client ID. For creating an application go to this page.
Select Anonymous usage without user authorization option as Authorization Type.

Fill up all the other fields including CAPTCHA. Then click submit button.
You will now get a client ID and a client Secret key. We will only need a client ID.

Create One File Name index.php And Copy The Code Below.

<!doctype html>
<html lang="en">
<head>
   <title>Online Image Uploader - with PHP using IMGUR</title>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
   <link rel="stylesheet" href="css/style.css?v=1">
</head>
<body>
<div class="container">
<h2 class="text-center">Imgur PHP Image Uploader</h2>
<hr/>
<div class="row">
<form class="col-sm" action="" enctype="multipart/form-data" method="POST">
<h4>Upload Image : </h4>
<div class="uploader" onclick="$('#filePhoto').click()">
<div class="innerUploader">
    Select Image
    <img class="hidden" src="" />
    <input accept="image/*" type="file" name="img"  id="filePhoto" />
</div>
</div>
 <input type="submit" name="submit" value="Upload" />
</form>
<div class="col-sm">
<?php
if(isset($_POST['submit'])){ 
 $img=$_FILES['img']; 
 if($img['name']==''){  
  echo "<h2>Select an Image Please.</h2>";
 }
 else {
  $filename = $img['tmp_name'];
  $client_id='67fd839d20ce847';		// Replace this with your client_id, if you want images to be uploaded under your imgur account
  $handle = fopen($filename, 'r');
  $data = fread($handle, filesize($filename));
  $pvars = array('image' => base64_encode($data));
  $timeout = 30;
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
  curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

  $out = curl_exec($curl);
  curl_close ($curl);
  $pms = json_decode($out,true);
  $url=$pms['data']['link'];
  if($url!=''){
   echo "<h4 bg-success>Uploaded Without Any Problem</h4>";
   echo "<input type='text' id='image-link' value='".substr($url,8)."'/><button onclick='copyToClipboard()'>Copy link</button><br/><hr/><h5>Preview : </h5>";
   echo "<img id='imgur-image' alt='imgur-image' src='$url'/>";
  }
  else{
   echo "<h4 class='bg-danger'>There’s a Problem</h4>";
   echo "<div>".$pms['data']['error']."</div>";  
  } 
 }
}
?>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var imageLoader = document.getElementById('filePhoto');
imageLoader.addEventListener('change', handleImage, false);

function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        $('.innerUploader img').attr('src',event.target.result).removeClass("hidden" );
    }
    reader.readAsDataURL(e.target.files[0]);
}

function copyToClipboard() {
  var copyText = document.getElementById("image-link");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the link: " + copyText.value);
}
</script>
</body>
</html>

Search.php

<form action="" method="get">
  <input name="imageHash" type="text" />
  <input type="submit" value="Search" />
</form>
<?php
if(isset($_GET['imageHash'])) {
$curl = curl_init();
$clientId = "67fd839d20ce847";
$imageHash = $_GET['imageHash'];
echo $imageHash;

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.imgur.com/3/gallery/search/top/1/".$imageHash,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Client-ID {$clientId}"
  ),
));
$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo "Response: ".$response;
  echo "Data : ".$response["data"];
}
}
?>

Create folder named css. And Create File Named Style.css.

	@import url('https://fonts.googleapis.com/css?family=Concert+One');
	body {
	  font-family: 'Concert One', cursive;
	}
	.uploader {
	  display:table;
	  position:relative;
	  overflow:hidden;
	  width:300px;
	  height:300px;
	  background:#f3f3f3;
	  border:2px dashed #e8e8e8;
	}
	.innerUploader {
	  display:table-cell;
	  position:relative;
	  outline:2px dashed red;
	  outline-offset: -3px;
	  justify-content:center;
	  align-items:center;
	  overflow:hidden;
	  vertical-align:middle;
	  text-align:center;
	}
	#filePhoto{
	    position:absolute;
	    width:290px;
	    height:290px;
	    top:-5px;
	    left:0;
	    z-index:2;
	    opacity:0;
	    cursor:pointer;
	}
	.uploader img{
	    position:absolute;
	    height:300px;
	    width:300;
	    top:-1px;
	    left:-1px;
	    z-index:1;
	    border:none;
	    min-width:100%;
	    min-height:100%;
	}
	#imgur-image{
	    max-width:100%;
	}
	.hidden {
	  display:none;
	}   

Now upload these files to your server .Upload file to imgur using php and retrieve the link

View Live Demo