Git Product home page Git Product logo

php-imgur-api-client's Introduction

PHP Imgur API Client

CI Coverage Status Total Downloads License

Object Oriented PHP wrapper for the Imgur API.

Uses Imgur API v3.

Information

  • Branch 1.x use Guzzle 3 (but is not maintained)
  • Branch 2.x use Guzzle 5 (but is not maintained)
  • Branch 3.x use Guzzle 6 and PHP >= 5.6
  • Branch master use Guzzle 7 and PHP >= 7.4

Composer

Download Composer

$ curl -s http://getcomposer.org/installer | php

Add the library details to your composer.json

composer require j0k3r/php-imgur-api-client@^4.0

Install the dependency with

$ php composer.phar install

Basic usage

// This file is generated by Composer
require_once 'vendor/autoload.php';

$client = new \Imgur\Client();
$client->setOption('client_id', '[your app client id]');
$client->setOption('client_secret', '[your app client secret]');

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);

    if ($client->checkAccessTokenExpired()) {
        $client->refreshToken();
    }
} elseif (isset($_GET['code'])) {
    $client->requestAccessToken($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
} else {
    echo '<a href="'.$client->getAuthenticationUrl().'">Click to authorize</a>';
}

The API calls can be accessed via the $client object

$memes = $client->api('memegen')->defaultMemes();

Documentation

Basic information

This client follow the same tree as the Imgur API.

Here is the list of available endpoints: account, album, comment, custom gallery, gallery, image, conversation, notification, memegen & topic.

You can access each endpoint using the api() method:

$client->api('album');
$client->api('comment');
$client->api('customGallery');
// etc ...

All available methods for each endpoints are in the folder Api. They mostly follow the description name in the Imgur doc. Here are few examples:

// for "Account Base" in account
$client->api('account')->base();
// for "Account Gallery Profile" in account
$client->api('account')->accountGalleryProfile();

// for "Filtered Out Gallery" in Custom Gallery
$client->api('customGallery')->filtered();

// for "Random Gallery Images" in gallery
$client->api('gallery')->randomGalleryImages();

// etc ...

Uploading an image

If you want to upload an image you can use one of these solutions:

$pathToFile = '../path/to/file.jpg';
$imageData = [
    'image' => $pathToFile,
    'type'  => 'file',
];

$client->api('image')->upload($imageData);

or

$urlToFile = 'http://0.0.0.0/path/to/file.jpg';
$imageData = [
    'image' => $urlToFile,
    'type'  => 'url',
];

$client->api('image')->upload($imageData);

or

$pathToFile = '../path/to/file.jpg';
$imageData = [
    'image' => base64_encode(file_get_contents($pathToFile)),
    'type'  => 'base64',
];

$client->api('image')->upload($imageData);

Pagination

For any API call that supports pagination and is not explicitly available via the method parameters, it can be achieved by using the BasicPager object and passing it as the second parameter in the api() call.

$pager = new \Imgur\Pager\BasicPager(1, 10);
$images = $client->api('account', $pager)->images();

Here is a real life example if you want to retrieve all your available images of an account:

$page = 1;
$pager = new \Imgur\Pager\BasicPager();
$res = $client->api('account', $pager)->images();

while (!empty($res)) {
    // var_dump(count($res));

    $pager->setPage($page++);

    $res = $client->api('account', $pager)->images();
}

This pager is really basic:

  • You won't have information about how many pages are available
  • If you request a non-existant page, you'll get an empty array

NOTE: /gallery endpoints do not support the perPage query string, and /album/{id}/images is not paged.

Please, read the Imgur doc about it.

Image id or Album id ?

When you got an Imgur link it's almost impossible to be 100% sure if it's an image or an album. That's why we have an endpoint which might fix that by first checking an id as an image and if it's fail, test it as an album:

$data = $client->api('albumOrImage')->find($id);

License

php-imgur-api-client is licensed under the MIT License - see the LICENSE file for details

php-imgur-api-client's People

Contributors

adyg avatar alfredoramos avatar dependabot[bot] avatar harryqt avatar j0k3r avatar mechpave avatar peter279k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

php-imgur-api-client's Issues

Error exception 'Undefined index: request' when invoking to upload image

I am using the 'j0k3r/php-imgur-api-client' package in my laravel project. The installation of it seems to be good and lucky. And I wrote a test seeder script(UnitTestSeeder.php) and a class (ImgurClient.php) as followed

use Illuminate\Database\Seeder;  

use App\Libs\Service\ImgurClient;    

class UnitTestSeeder extends Seeder{

    public function run(){  

        $username = 'your_imgur_username';

        $id = 'Iemhfpo';

        //$response = $this->galleryFavorites($username);//run ok

        //$response = $this->favorites($username);// run ok

        //$response = $this->randomGalleryImages();//run ok

        //$response = $this->uploadImage();//run error        
        //$response = $this->createAlbum();//run error

        print_r($response);
    }

    private function uploadImage(){
        $client = new ImgurClient();
        $fpath = storage_path('app/public/test.jpg');
        $imageData = ['image' => $fpath, 'type'  => 'file'];

        return $client->upload($imageData);
    }
    private function createAlbum(){
        $client = new ImgurClient();
        $album_data = [];
        $album_data['title'] = 'Bracelet';
        $album_data['description'] = 'Beautiful Bracelet';
        $album_data['privacy'] = 'public';
        $album_data['layout'] = 'grid';

        return $client->createAlbum($album_data);
    }
    private function randomGalleryImages(){
        $client = new ImgurClient();
        return $client->randomGalleryImages();
    }
    private function galleryFavorites($username){
        $client = new ImgurClient();
        return $client->galleryFavorites($username);
    }
    private function favorites($username){
        $client = new ImgurClient();
        return $client->favorites($username);
    }

But saddly, as the code comments showed above, Some API calls can't work and some other API calls work well.
The 2 calls(createAlbum and uploadImage) throwed exceptions as the screenshot showed here

Anybody have encountered such errors? Thanks all!

Check if ID is image or album?

Is it possible to check if a given ID is an image or album? How else would I know to use image($imageId) or album($albumId) without first knowing that?

Image upload POST request removes multipart/form-data parameters

The PR #35 introduced a bug that ignores all parameters passed to the endpoint https://api.imgur.com/3/upload except for type and image, so parameters such as name, album, description, etc., are removed from the payload.

Here's the $data passed to Imgur\Api\Image::upload()

array(4) {
  ["image"]=>
  resource(227) of type (stream)
  ["type"]=>
  string(4) "file"
  ["name"]=>
  string(30) "Screenshot_20211129_113548.png"
  ["album"]=>
  string(5) "XXXXX"
}

Here's the generated value of $options in Imgur\HttpClient\HttpClient::performRequest():

array(3) {
  ["headers"]=>
  array(0) {
  }
  ["body"]=>
  string(0) ""
  ["multipart"]=>
  array(2) {
    [0]=>
    array(2) {
      ["name"]=>
      string(4) "type"
      ["contents"]=>
      string(4) "file"
    }
    [1]=>
    array(2) {
      ["name"]=>
      string(5) "image"
      ["contents"]=>
      resource(227) of type (stream)
    }
  }
}

OAuth2.php can't get access_token

The token sometimes comes back in the form $token['data']['access_token'] so we need to check if it is there and use that instead.

Upload not working

Hello , I am trying to upload to Imgur account , but it seems not working, I dont get any error code too.This is the call back returned :

Basic {#223 ▼
  -data: []
  -success: false
  -status: null
}

Add support for "token" as authorization response type

Currently pin and code are deprecated according to the Imgur docs:

The code and pin response types have been deprecated and will soon no longer be supported

And the library does not accept the new token for response_type:

public function requestAccessToken($code, $requestType)
{
switch ($requestType) {
case 'pin':
$grantType = 'pin';
$type = 'pin';
break;
case 'code':
default:
$grantType = 'authorization_code';
$type = 'code';
}

I've been lately receiving HTTP 500 responses from Imgur, I'm not sure if that's because of that API change.

Comment model need updated.

"Caption" references should be updated to "Comment" in Comment model. Also, non-existent function setComments() needs updated to setChildren().

Imgur has recently renamed "captions" to the better suited term "comments." This would be a benign issue, except they have updated their API response parameter from "caption" to "comment" which breaks this API client.

Additionally, the Comment model references a function that doesn't actually exist, setComments(). The actual function name which accomplishes the desired effect is setChildren().

For a patch, please look at my fork's commit here.

I forked instead of issuing pull request because I need this working tonight, and also I'm building some custom functions into this library as well.

Thanks for building this.

getGifv() for images?

I noticed that the imgur model for image has a lot more properties than those I see provided in this library, like gifv, mp4, webm, etc.

How can I retrieve these properties using this library?

Error handling when uploading too fast

It seems they rate limit how often you can upload.

Error has occured in file j0k3r/php-imgur-api-client/lib/Imgur/Middleware/ErrorMiddleware.php on line 74:

"Request to: /3/image failed with: "429,You are uploading too fast. Please wait 16 more minutes.,ImgurException,Array"

Example of use livewire 3

I would like to see a complete example of how to use this package with Laravel and Livewire. Please

Image uploading API with file should be multipart/form-data header

As title, when using the Imgur client to upload image, it should throw following exception:

PHP Fatal error:  Uncaught Imgur\Exception\ErrorException: Request to: /3/image failed with: "Invalid URL (@Resource id #50)" in /data/php-imgur-api-client/lib/Imgur/Middleware/ErrorMiddleware.php:91
Stack trace:
#0 /data/php-imgur-api-client/lib/Imgur/Middleware/ErrorMiddleware.php(35): Imgur\Middleware\ErrorMiddleware->checkError(Object(GuzzleHttp\Psr7\Response))
#1 /data/php-imgur-api-client/vendor/guzzlehttp/promises/src/FulfilledPromise.php(41): Imgur\Middleware\ErrorMiddleware->Imgur\Middleware\{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /data/php-imgur-api-client/vendor/guzzlehttp/promises/src/TaskQueue.php(48): GuzzleHttp\Promise\FulfilledPromise::GuzzleHttp\Promise\{closure}()
#3 /data/php-imgur-api-client/vendor/guzzlehttp/promises/src/Promise.php(248): GuzzleHttp\Promise\TaskQueue->run(true)
#4 /data/php-imgur-api-client/vendor/guzzlehttp/promises/src/Promise.php(224): GuzzleHttp\Promise\Promise->invokeWaitFn()
#5 /data/php-imgur-api-client/vendor/guzzlehttp/promises/src/Promise.php(269): GuzzleHttp\Promise\Promi in /data/php-imgur-api-client/lib/Imgur/Middleware/ErrorMiddleware.php on line 91

The reproduced codes are as follows:

<?php

require __DIR__ . '/vendor/autoload.php';

use Imgur\Client;

$client = new Client();

$client->setOption('client_id', 'client_id');
$client->setOption('client_secret', 'client_secret');

$test = $client->api('image')->upload([
    'image' => __DIR__ . '/1.jpg',
    'type' => 'file',
]);
var_dump($test);

After looking at the official Imgur API doc, using the image file path and type is file should use the multipart/form-data to be the request header, not the form_params (the application/x-www-form-urlencoded header).

Not returning images when is an album

When fetching frontpage gallery images, if 'isAlbum' is true it returns null in 'images'. Still, it can return the count of images inside the album.

Unable to get local issuer certificate

Hey there,

Having a problem while using the library on localhost:
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

I've searched a way to disable SSL verification in Guzzle, but I wasn't able to find how I can pass request options to Guzzle from the HttpClient, do you have an idea ?

Here is my code:

    /**
     * @Rest\Post("/images")
     * @Rest\FileParam(name="image", nullable=false, image=true)
     * @param ParamFetcherInterface $params
     */
    public function imageUpload(ParamFetcherInterface $params) {
        $this->denyAccessUnlessGranted('ROLE_ADMIN');

        $client = new Client();
        $client->setOption("client_id", $_ENV["IMGUR_CLIENT_ID"]);
        $client->setOption("client_secret", $_ENV["IMGUR_CLIENT_SECRET"]);

        $test = $client->api('image')->upload(array(
            'image' =>  $params->get('image'),
            'type'  =>  'file'
        ));

        print_r($test);
    }

Problem with submitToGallery($pic['id'],$data)

Hi,
everything works fine but unfortunatly I get an error when using this function:

$client->api('gallery')->submitToGallery($pic['id'],$data);

Error:
Fatal error: Uncaught TypeError: Imgur\HttpClient\HttpClient::parseResponse(): Return value must be of type array, bool returned in /www/htdocs/w019a155/mysite/imgur/vendor/j0k3r/php-imgur-api-client/lib/Imgur/HttpClient/HttpClient.php:116
Stack trace:
#0 /www/htdocs/w019a155/mysite/imgur/vendor/j0k3r/php-imgur-api-client/lib/Imgur/Api/AbstractApi.php(58): Imgur\HttpClient\HttpClient->parseResponse(Object(GuzzleHttp\Psr7\Response))
#1 /www/htdocs/w019a155/mysite/imgur/vendor/j0k3r/php-imgur-api-client/lib/Imgur/Api/Gallery.php(231): Imgur\Api\AbstractApi->post('gallery/1tGNf19', Array)
#2 /www/htdocs/w019a155/mysite/imgur/authenticationCallBack.php(50): Imgur\Api\Gallery->submitToGallery('1tGNf19', Array)
#3 {main}
thrown in /www/htdocs/w019a155/mysite/imgur/vendor/j0k3r/php-imgur-api-client/lib/Imgur/HttpClient/HttpClient.php on line 116

Do you have an explanation?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.