phpjsonimgur

fetching imgur cURL to json_decode php upload form


I'm trying to use imgur as a uploading backend - I guess it secure my website if there's upload picture (is it right?) so I went with this way:

<?php

$client_id = 'xxxxx';

    $file = file_get_contents($_FILES["imgupload"]["tmp_name"]);

    $url = 'https://api.imgur.com/3/image.json';
    $headers = array("Authorization: Client-ID $client_id");
    $pvars = array('image' => base64_encode($file));

    $curl = curl_init();

    curl_setopt_array($curl, array(
       CURLOPT_URL=> $url,
       CURLOPT_TIMEOUT => 30,
       CURLOPT_POST => 1,
       CURLOPT_RETURNTRANSFER => 1,
       CURLOPT_HTTPHEADER => $headers,
       CURLOPT_POSTFIELDS => $pvars
    ));

    if ($error = curl_error($curl)) {
        die('cURL error:'.$error);
    }

    $json_returned = curl_exec($curl); // blank response
    echo "Result: " . $json_returned ;

    curl_close ($curl); 
?>

HTML form

  <form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="imgupload" /><br>
    <input type="submit" value="Upload to Imgur" />
</form>

When I click on submit the result is fine as I guess:

Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"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":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}

I want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.sstatic.net/79F8i.png'; to added into my database -> user pic

I went with json_decode but it's not completed with me in the right way.


Solution

  • json_decode worked fine here:

    $json_returned = json_decode($json_returned, true);
    $uploaded = $json_returned['data']['link'];