Upload Image to Imgur via API using PHP

Imgur is an online image hosting and sharing service provider. You can share images online via Imgur without hosting them on your server. If your web application has the image upload functionality and wants to optimize the server space, hosting the image to Imgur is the best way to use the image without hosting it on the server. The image files can be uploaded to Imgur and used Imgur image link to display on the website.

Imgur API provides a programmatic way to upload and manage images in the Imgur server. The Imgur API is a REST API service that accepts HTTP requests and returns JSON responses. You can integrate the Imgur API using PHP cURL. In this tutorial, we will show you how to upload images to Imgur via API and get image links from Imgur API using PHP.

Register Imgur Application

The Client ID is required to authenticate and use Imgur API. Before getting started with Imgur API create an application on your Imgur account to get a Client ID and Client Secret.

  • First, register for an Imgur account and sign in.
  • Register an application from the Imgur OAuth Client page – https://api.imgur.com/oauth2/addclient
    imgur-oauth-client-application-registration-codexworld
  • On successful App registration, the Client ID and Client secret will be generated. Collect Client ID to get started with the Imgur API.
  • You can get the Client ID from the App Settings page as well (https://imgur.com/account/settings/apps).
    imgur-account-app-settings-codexworld
  • This Client ID is required to be passed with an authorization header in the Imgur API request.
    'Authorization: Client-ID your-imgur-app-client-id'

Upload Image via Imgur API with PHP (Code Sample)

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

  • 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.
// Client ID of Imgur App 
$IMGUR_CLIENT_ID "YOUR_CLIENT_ID";

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

// Post image to Imgur via API
$ch curl_init();
curl_setopt($chCURLOPT_URL'https://api.imgur.com/3/image');
curl_setopt($chCURLOPT_POSTTRUE);
curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
curl_setopt($chCURLOPT_HTTPHEADER, array('Authorization: Client-ID ' $IMGUR_CLIENT_ID));
curl_setopt($chCURLOPT_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);

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

{
  "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
}

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.
<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>

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 

// 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($fileNamePATHINFO_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($chCURLOPT_URL'https://api.imgur.com/3/image');
            
curl_setopt($chCURLOPT_POSTTRUE);
            
curl_setopt($chCURLOPT_RETURNTRANSFERTRUE);
            
curl_setopt($chCURLOPT_HTTPHEADER, array('Authorization: Client-ID ' $IMGUR_CLIENT_ID));
            
curl_setopt($chCURLOPT_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/>');
    }
}

?>

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

<?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 ?>

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.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up