Search code examples
phpmysqlimagephotoimgur

How to implement imgur api (image host) on a website?


I came across http://api.imgur.com and thought that would be a usefull tool to use on my website. I then noticed that StackOwerflow uses it too, so it must be good ))) Although I'm struggling when I try to implement it. I took a look at http://api.imgur.com/examples the PHP section, but it didn't help me much.

What I'm interested in is includin imgur api on my website so users can upload their images. I would than need to store img url/path so I can display it on a website.

e.g. have a form that will allow users to upload photo, then store url/path of the uploaded image in a database (VARCHAR).

Has anyone had a success with this system and could help me understand how to implement it like StackOwerflow uses it (only store image url in database not post).

Code I tried:

 <form enctype="multipart/form-data" method="post" action="upload_img.php">
    Choose your file here:
    <input name="uploaded_file" type="file"/>
    <input type="submit" value="Upload It"/>
    </form>

upload_img.php

<?
    $filename = "image.jpg";
    $handle = fopen($filename, "r");
    $data = fread($handle, filesize($filename));

    // $data is file data
    $pvars   = array('image' => base64_encode($data), 'key' => IMGUR_API_KEY);
    $timeout = 30;
    $curl    = curl_init();

    curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

    $xml = curl_exec($curl);

    curl_close ($curl);
?>

Solution

  • I see that you have copy and pasted the example from the imgur API site, which gives the example of a filename which is contained within $filename. You need to point this variable at the file that PHP has uploaded.

    Modify the $filename part of your script:

    $filename = $_FILES['uploaded_file']['tmp_name'];
    

    Source: POST method file uploading