How to Upload Image to Imgur via API using PHP

Upload Image to Imgur via API using PHPImgur is an online Image Sharing American website that provides Image Hosting Services for free.Any Internet user from anywhere in the world can host their images using Imgur. And from this website, they can also generate the URL of the image for free.
You can publish the image from the generated URL anywhere on the Internet, mostly Reddit, Twitter and Digg users use the Imgur website a lot for Image Sharing. This website is like an online sharing image community where you will get to see viral images, GIFs, Memes.

If you have a web application that has the functionality to use imgur, then its a great news you can optimize your server space by uploading your images to imgur and then embed it on your website. All the images will be served from imgur server. To make this uploading and managing of images in imgur you can use imgur API, imgur API provides you a programmatic way to upload and manages your images in imgur server. Imgur API works as a Rest API service which accepts HTTP requests and generate JSON responses. We can implement the Imgur API using PHP cURL. In this tutorial, we will explain you how you can upload images using Imgur API and how to get image URL from Imgur API using PHP.

How to Upload Image to Imgur via API using PHP

Before directly going to Imgur API first of all create an Imgur Application so that you can get a Client ID and Client Secret, Client ID will be necessary to authenticate Imgur API. Kindly follow the below steps:

  • First, register for an Imgur account and sign in.
  • Register an Application from the Imgur OAuth Client page – Click Here

Imgur OAuth Client page

  • After successful registration, Client ID and Client Secret will be generated as shown below. Now note it and will start with Imgur API.
  • You can get the Client ID from the App Settings page as well (https://imgur.com/account/settings/apps).

imgure client id

  • This Client ID is required to be passed with an authorization header in the Imgur API request.
'Authorization: Client-ID YOUR_CLIENT_ID'

Upload Image via Imgur API with PHP (Source Code)

In the below example, we will use Imgur API to upload images and get the image Links.

    • Specify the Client ID to be used for Authorization.
    • Get data from source image using PHP file_get_contents().
    • Use PHP cURL to post images to Imgur API (API URL: https://api.imgur.com/3/image).
  • Fetch API response and decode to array using json_decode() function in PHP.
  • Retrieve image link URL from API response using PHP.

[php]
// Client ID of Imgur App
$IMGUR_CLIENT_ID = "YOUR_CLIENT_ID";

// Source image
$image_source = file_get_contents("images/GeekyBeginners-image.jpg");

// Post image to Imgur via API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://api.imgur.com/3/image’);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Authorization: Client-ID ‘ . $IMGUR_CLIENT_ID));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(‘image’ => base64_encode($image_source)));
$response = curl_exec($ch);
curl_close($ch);

// Decode API response to array
$responseArr = json_decode($response);

// Print API response
print ‘<pre>’; print_r($responseArr); print ‘</pre>’;

// Display image from Imgur
printf(‘<img height="180" src="%s" >’, $responseArr->data->link);
[/php]

API Response:
On successful upload, the Imgur API will return the following response in JSON format.

[xml]{
"data": {
"id": "rwYHrBN",
"title": null,
"description": null,
"datetime": 1649096564,
"type": "image/jpeg",
"animated": false,
"width": 640,
"height": 400,
"size": 78307,
"views": 0,
"bandwidth": 0,
"vote": null,
"favorite": false,
"nsfw": null,
"section": null,
"account_url": null,
"account_id": 0,
"is_ad": false,
"in_most_viral": false,
"has_sound": false,
"tags": [],
"ad_type": 0,
"ad_url": "",
"edited": "0",
"in_gallery": false,
"deletehash": "addXM7EZF2UPGlp",
"name": "",
"link": "https://i.imgur.com/rwYHrBN.jpg"
},
"success": true,
"status": 200
}[/xml]

Image Upload with Imgur API using PHP (Working Example)

This example script shows how to integrate Imgur API in the image upload form to upload and embed images on the webpage without hosting on the server.

HTML Upload Form:
This HTML form allows you to select an image file to upload and input value for some optional fields.

  • Define HTML elements that
    • Allow selecting image files to upload.
    • Allow to input the title and description text.
  • The <form> tag must contain the enctype="multipart/form-data" attribute to post image data.

[html]<form method="post" action="" class="form" enctype="multipart/form-data">
<div class="form-group">
<label>Image</label>
<input type="file" name="image" class="form-control"> </div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control"> </div>
<div class="form-group">
<label>Description</label>
<input type="text" name="description" class="form-control"> </div>
<div class="form-group">
<input type="submit" class="form-control btn-primary" name="submit" value="Upload to Imgur" /> </div>
</form>[/html]

On form submission, the form will be posted to the server-side (upload.php) script to process further.

Upload Image with Imgur API (upload.php):
This server-side script handles the file upload process with Imgur API using PHP.

    • Get image data from the form’s input using PHP $_FILES.
    • Get some additional info (title and description) from the form’s input using PHP $_POST.
    • Retrieve data from image using file_get_contents() in PHP.
    • Encode image data to base64 string using base64_encode() function in PHP.
    • Execute cURL request to post image to Imgur API using PHP.
  • Get image link from API response (data->link).

[php]</pre>
<?php

// Client ID of Imgur App
$IMGUR_CLIENT_ID = "YOUR_CLIENT_ID";

$statusMsg = $valErr = ”;
$status = ‘danger’;
$imgurData = array();

// If the form is submitted
if (isset($_POST[‘submit’]))
{

// Validate form input fields
if (empty($_FILES["image"]["name"]))
{
$valErr .= ‘Please select a file to upload.<br/>’;
}

// Check whether user inputs are empty
if (empty($valErr))
{
// Get file info
$fileName = basename($_FILES["image"]["name"]);
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);

// Allow certain file formats
$allowTypes = array(
‘jpg’,
‘png’,
‘jpeg’,
‘gif’
);
if (in_array($fileType, $allowTypes))
{
// Source image
$image_source = file_get_contents($_FILES[‘image’][‘tmp_name’]);

// API post parameters
$postFields = array(
‘image’ => base64_encode($image_source)
);

if (!empty($_POST[‘title’]))
{
$postFields[‘title’] = $_POST[‘title’];
}

if (!empty($_POST[‘description’]))
{
$postFields[‘description’] = $_POST[‘description’];
}

// Post image to Imgur via API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘https://api.imgur.com/3/image’);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Authorization: Client-ID ‘ . $IMGUR_CLIENT_ID
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$response = curl_exec($ch);
curl_close($ch);

// Decode API response to array
$responseArr = json_decode($response);

// Check image upload status
if (!empty($responseArr
->data
->link))
{
$imgurData = $responseArr;

$status = ‘success’;
$statusMsg = ‘The image has been uploaded to Imgur successfully.’;
}
else
{
$statusMsg = ‘Image upload failed, please try again after some time.’;
}
}
else
{
$statusMsg = ‘Sorry, only an image file is allowed to upload.’;
}
}
else
{
$statusMsg = ‘<p>Please fill all the mandatory fields:</p>’ . trim($valErr, ‘<br/>’);
}
}

?>
<pre> [/php]

Display Image from Imgur:
Retrieve link from API response to embed and display the image with Imgur URL on the webpage.

[php]<?php if (!empty($imgurData))
{ ?>
<div class="card">
<img src="<?php echo $imgurData
->data->link; ?>" class="card-img-top" alt="…">
<div class="card-body">
<h5 class="card-title"><?php echo $imgurData
->data->title; ?></h5>
<p class="card-text"><?php echo $imgurData
->data->description; ?></p>
<p><b>Imgur URL:</b> <a href="<?php echo $imgurData
->data->link; ?>" target="_blank"><?php echo $imgurData
->data->link; ?></a></p>
</div>
</div>
<?php
} ?>
[/php]

Conclusion

The image upload with Imgur API is very useful when you don’t want to increase the load on storage space by storing the uploaded images on the server. You can upload images to Imgur via API dynamically and access the images on the website using PHP. This example script helps you to upload images to Imgur via API, generate image links, and embed or display images on the web page using PHP.

Write for us
GeekyBeginners articles are written by software geeks like you. If you also would like to contribute to GeekyBeginners by writing paid articles, you can check the write for us page.