Giter Site home page Giter Site logo

samwilson / phpflickr Goto Github PK

View Code? Open in Web Editor NEW
38.0 7.0 15.0 401 KB

A PHP wrapper for the Flickr API, including OAuth.

Home Page: https://packagist.org/packages/samwilson/phpflickr

License: GNU General Public License v2.0

PHP 100.00%
flickr-api flickr php libraries hacktoberfest

phpflickr's Introduction

PhpFlickr

A PHP wrapper for the Flickr API.

https://github.com/samwilson/phpflickr

Packagist

Build status

Table of contents:

Installation

Install with Composer:

composer require samwilson/phpflickr

Usage

Once you've included Composer's autoloader, create a PhpFlickr object. For example:

require_once 'vendor/autoload.php';
$flickr = new \Samwilson\PhpFlickr\PhpFlickr($apiKey, $apiSecret);

The constructor takes two arguments:

  1. $apiKey — This is the API key given to you by Flickr when you register an app.

  2. $secret — The API secret is optional because it is only required to make authenticated requests (see below). It is given to you along with your API key when you register an app.

All of the API methods have been implemented in phpFlickr. You can see a full list and documentation here: http://www.flickr.com/services/api/

To call a method, remove the "flickr." part of the name and replace any periods with underscores. For example, instead of flickr.photos.search, you would call $f->photos_search() or instead of flickr.photos.licenses.getInfo, you would call $f->photos_licenses_getInfo() (yes, it is case sensitive).

All functions have their arguments implemented in the list order on their documentation page (a link to which is included with each method in the phpFlickr clasS). The only exceptions to this are photos_search(), photos_getWithoutGeodata() and photos_getWithoutGeodata() which have so many optional arguments that it's easier for everyone if you just have to pass an associative array of arguments. See the comment in the photos_search() definition in phpFlickr.php for more information.

Examples

There are a few example files in the examples/ directory. To use these, first copy examples/config.dist.php to examples/config.php and run php examples/get_auth_token.php to get the access token. Add this access token to your examples/config.php and then you can run any of the examples that require authentication (note that not all of them do).

Authentication

There is only one user authentication method available to the API, and that is OAuth 1.0. You only need to use this if you're performing operations that require it, such as uploading or accessing private photos.

This authentication method is somewhat complex, but is secure and allows your users to feel a little safer authenticating to your application. You don't have to ask for their username and password.

Read more about the Flickr Authentication API.

We know how difficult this API looks at first glance, so we've tried to make it as transparent as possible for users of phpFlickr. We'll go through all of the steps you'll need to do to use this.

To have end users authenticate their accounts:

  1. Create an object in which to temporarily store the authentication token, and give it to PhpFlickr. This must be an implementation of TokenStorageInterface, and will usually be of type Session (for browser-based workflows) or Memory (for command-line workflows) — or you can create your own implementation.

    $storage = new \OAuth\Common\Storage\Memory();
    $flickr->setOauthStorage($storage);
  2. Send your user to a Flickr URL (by redirecting them, or just telling them to click a link), where they'll confirm that they want your application to have the permission you specify (which is either read, write, or delete).

    $perm = 'read';
    $url = $flickr->getAuthUrl($perm, $callbackUrl);
  3. Once the user has authorized your application, they'll either be redirected back to a URL on your site (that you specified as the callback URL above) or be given a nine-digit code that they'll need to copy and paste into your application.

    1. For the browser-based workflow, your callback URL will now have two new query-string parameters: oauth_token and oauth_verifier.
    2. For CLI workflow, you'll need to strip anything other than digits from the string that the user gives you (e.g. leading and trailing spaces, and the hyphens in the code).
  4. You can now request the final 'access token':

    1. For the browser-based workflow:
      $accessToken = $flickr->retrieveAccessToken($_GET['oauth_verifier'], $_GET['oauth_token']);
    2. For the CLI workflow, it's much the same, but because you've still got access to the request token you can leave it out when you run this request:
      $verifier = '<9-digit code stripped of hyphens and spaces>';
      $accessToken = $flickr->retrieveAccessToken($verifier);
  5. Now you can save the two string parts of the access token (which you can get via the $accessToken->getAccessToken() and $accessToken->getAccessTokenSecret() methods) and use this for future requests. The access token doesn't expire, and must be stored securely (the details of doing that are outside the scope of PhpFlickr).

Making authenticated requests

Once you have an access token (see above), you can store it somewhere secure and use it to make authenticated requests at a later time. To do this, first create a storage object (again, as for the initial authentication process, you can choose between different storage types, but for many situations the in-memory storage is sufficient), and then store your access token in that object:

// Create storage.
$storage = new \OAuth\Common\Storage\Memory();
// Create the access token from the strings you acquired before.
$token = new \OAuth\OAuth1\Token\StdOAuth1Token();
$token->setAccessToken($accessToken);
$token->setAccessTokenSecret($accessTokenSecret);
// Add the token to the storage.
$storage->storeAccessToken('Flickr', $token);

Now, you can pass the storage into PhpFlickr, and start making requests:

$flickr->setOauthStorage($storage);
$recent = $phpFlickr->photos()->getContactsPhotos();

See the Usage section above for more details on the request methods, and the examples/recent_photos.php file for a working example.

Caching

PhpFlickr can be used with any PSR-6 compatible cache, such as symfony/cache or tedivm/stash.

To enable caching, pass a configured cache object to PhpFlickr::setCache($cacheItemPool).

All requests are cached for the same time duration, which by default is 10 minutes. This can be changed with the PhpFlickr::setCacheDefaultExpiry().

Uploading

Uploading new photos

Uploading is pretty simple. Aside from being authenticated (see the Authentication section above) the very minimum that you'll have to pass is a path to an image file. You can upload a file as follows:

$flickr->uploader()->upload('/path/to/photo.jpg');

The other upload parameters are documented in the method's docblock. One useful one is the $async flag, which permits asyncronous uploading, which means that, rather than uploading the file immediately and before returning, a 'ticket ID' is returned, with which you can subsequently fetch the upload's status. You can read more about asynchronous uploading in Flickr's API documentation.

Replacing existing photos

You can also upload a photo as a replacement to an existing photo.

$flickr->uploader()->replace('/path/to/photo.jpg', 44333812150);

This method doesn't allow for setting any photo metadata, but you can do the replacement asynchronously (in which case a 'ticket ID' will be returned).

User Agent

If you are using PhpFlickr in an application, it is a good idea to set a custom user agent. This can be done with the following:

$flickr->setUserAgent('MyVendor-MyApp/1.0.0');

Proxy server

PhpFlickr can be used with a proxy server or any service that matches Flickr's API (such as 23 Photo Sharing). To use this feature, pass the proxy server's base URL after instantiating a PhpFlickr object. For example:

$flickr->setProxyBaseUrl('http://localhost:8181/flickr');

After that, all requests will be automatically made through your proxy server.

One example of configuring such a proxy service, for the Apache webserver, is as follows:

ProxyRequests Off
SSLProxyEngine on
ProxyPass /flickr https://api.flickr.com/services
ProxyPassReverse /flickr https://api.flickr.com/services

Kudos

This is a fork of Dan Coulter's original phpFlickr library, maintained by Sam Wilson. All the hard work was done by Dan!

Thanks also is greatly due to the many other contributors.

The Agateware_Example.JPG used for the upload examples is CC-BY-SA by User:Anonymouse512, via Wikimedia Commons.

phpflickr's People

Contributors

alerque avatar benjaminchodroff avatar calebdre avatar carlos-mg89 avatar dan-coulter avatar dependabot-preview[bot] avatar dependabot[bot] avatar fbianco avatar mikemtol avatar mistic100 avatar nogorilla avatar samwilson avatar scotthorn avatar sillygwailo avatar stevenmaguire avatar vojtasvoboda 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpflickr's Issues

buildPhotoURL() shouldn't break if original isn't available

When downloading a photo which doesn't have an original size available, buildPhotoURL() should return false.

Also, we should add some sort of 'max available' size, because that's usually what we're looking for when we ask for original.

Too few arguments to function Samwilson\PhpFlickr\PhotosApi::search()

when I send an array argument to photos_search function , it throws this error

Too few arguments to function Samwilson\PhpFlickr\PhotosApi::search(), 0 passed in C:\xampp\htdocs\gallery\vendor\samwilson\phpflickr\src\PhpFlickr.php on line 1376 and exactly 1 expected

For this line

$photos = $flickr->photos_search(array( 'api_key' => 'dfghddfd', 'tags' => 'cars' ));

ideas for next version: error handling and return types

 public function getPhotos(
        $photosetId,
        $userId = null,
        $extras = null,
        $perPage = null,
        $page = null,
        $privacyFilter = null,
        $media = null
    ) 

With PHP 8, we'll want to add a return type to the methods. Currently in getPhotos(), this is array|bool, but we could make it ?array, and return null instead of false.

It appears that returning false indicates some sort of error, though, so perhaps that's not the best approach.

Example for multi upload and add photo set?

Hello everyone and the author,

Can you help me for example of multi upload and add photo set after upload? I tried it but it responded like this.

I can pay for it to show gratitude.

Thanks for that!
47684705_1269029973239038_7721016897898020864_n

Not Getting "oauth_verifier" From $flickr->getAuthUrl($perm, $callbackUrl);

This is my code:

`require_once 'vendor/autoload.php';
$apiKey = "6cc27cfb0c759011b11a48e456d8ba74";
$apiSecret = "6169a34168fae718";
$flickr = new \Samwilson\PhpFlickr\PhpFlickr($apiKey, $apiSecret);

$storage = new \OAuth\Common\Storage\Memory();
$flickr->setOauthStorage($storage);

$perm = 'write';
$callbackUrl = false;
$url = $flickr->getAuthUrl($perm, $callbackUrl);`

am not getting 'oauth_verifier' From $flickr->getAuthUrl($perm, $callbackUrl);

My Output

OAuth\Common\Http\Uri\Uri Object ( [scheme:OAuth\Common\Http\Uri\Uri:private] => https [userInfo:OAuth\Common\Http\Uri\Uri:private] => [rawUserInfo:OAuth\Common\Http\Uri\Uri:private] => [host:OAuth\Common\Http\Uri\Uri:private] => api.flickr.com [port:OAuth\Common\Http\Uri\Uri:private] => 443 [path:OAuth\Common\Http\Uri\Uri:private] => /services/oauth/authorize [query:OAuth\Common\Http\Uri\Uri:private] => oauth_token=72157710566803341-1250e3b8a7496c87&perms=write [fragment:OAuth\Common\Http\Uri\Uri:private] => [explicitPortSpecified:OAuth\Common\Http\Uri\Uri:private] => [explicitTrailingHostSlash:OAuth\Common\Http\Uri\Uri:private] => )

How to get 'oauth_token' from this array?
demo php

Remove non-PSR6 caching

Now we support PSR6 caches, there's no need to directly support database, filesystem, or other custom caching (the latter hasn't been able to be used since v3 anyway).

token_rejected

Hello,

Im' facing to an issue when I try to authentificate with oAuth. I manage to get a couple of token/verifier back from FlickR in my web app (under development, so hosted in my localhost).

But unfortunately, when I try the method retrieveAccessToken(), I get a "token_rejected" error, and 4 notices like Notice: Undefined index: oauth_token in C:\wamp64\www\flickr\vendor\lusitanian\oauth\src\OAuth\OAuth1\Service\Flickr.php on line 67

Is there someting I missed? Any help is appreciated :-)

My full code below :

<?php 
	session_start();
	
	// OBJET FLICKR
	// ------------
	require_once 'vendor/autoload.php';
	
	$apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
	$apiSecretKey = "yyyyyyyyyyyyyyyy";
	
	$f = new \Samwilson\PhpFlickr\PhpFlickr($apiKey, $apiSecretKey);
	$storage = new \OAuth\Common\Storage\Session();
	$f->setOauthStorage($storage);
	
	// SESSION STORING
	// ---------------
	if(isset($_GET['oauth_verifier']))
		$_SESSION['oauth_verifier'] = $_GET['oauth_verifier'];

	if(isset($_GET['oauth_token']))
		$_SESSION['oauth_token'] = $_GET['oauth_token'];

	// GENERATE TOKEN IF NEEDED
	// ------------------------
	if(!isset($_SESSION['oauth_verifier'])){
	
		$perm = 'read';
		$callbackUrl = null;	// Renvoie vers la même page
		$url = $f->getAuthUrl($perm, $callbackUrl);
		header('Location: '.$url->getAbsoluteUri());
	
		
	// CONNEXION WITH TOKEN
	// --------------------
	} else{
		$accessToken = $f->retrieveAccessToken($_SESSION['oauth_verifier'], $_SESSION['oauth_token']);
		var_dump($accessToken);
	}

Thanks !

delete returns oauth_problem=verifier_invalid

Hi
Thank you for maintaining this class... I am new to it but making progress everyday!

I successfully implement the oAuth to get an access token & secret based on the example provided (get_auth_token.php). I can get private photos, so it is working.

I need to delete media at Flickr. That returns an error : Unable to decode Flickr response to flickr.photos.delete request: oauth_problem=verifier_invalid. BTW, I had a similar error when trying to use getRecent. I am on Laravel.

Here is my code...

$accessToken = "xxx";
$accessTokenSecret = "xxx";

$token = new \OAuth\OAuth1\Token\StdOAuth1Token();
$token->setAccessToken($accessToken);
$token->setAccessTokenSecret($accessTokenSecret);
$storage = new \OAuth\Common\Storage\Memory();
$storage->storeAccessToken('Flickr', $token);

$phpFlickr = new \Samwilson\PhpFlickr\PhpFlickr(['flickrKey'],['flickrSecret']);

$phpFlickr->setOauthStorage($storage);

$result = $phpFlickr->photos()->delete($id);

Drop unsupported dependencies

This library could take advantage of some of the goodies in PHP 8 by dropping support for PHP 7.

You could tag this as version 1 (for BC), then use rector to refactor and take advantage of better type-hinting, return types, etc.

New 6K display size support

Greetings Sam, a question about the 6K image support flickr is offering to Pro members. Any additional information on this?

Fatal error when trying to run get_auth_token.php in examples

Relatively new to this, so it may be something simple I'm missing, but I've copied the config.php file and updated the $apiKey and $apiSecret with my own, and can run the unauthenticated_requests.php example, but when trying to run the get_auth_token.php file, it returns:

Fatal error: Uncaught OAuth\Common\Http\Exception\TokenResponseException: Error in retrieving token. in C:\xampp\htdocs\photos\vendor\lusitanian\oauth\src\OAuth\OAuth1\Service\Flickr.php:52 Stack trace: #0 C:\xampp\htdocs\photos\vendor\lusitanian\oauth\src\OAuth\OAuth1\Service\AbstractService.php(54): OAuth\OAuth1\Service\Flickr->parseRequestTokenResponse('oauth_problem=s...') #1 C:\xampp\htdocs\photos\vendor\samwilson\phpflickr\src\PhpFlickr.php(560): OAuth\OAuth1\Service\AbstractService->requestRequestToken() #2 C:\xampp\htdocs\photos\examples\get_auth_token.php(32): Samwilson\PhpFlickr\PhpFlickr->getAuthUrl('delete', 'http://localhos...') #3 {main} thrown in C:\xampp\htdocs\photos\vendor\lusitanian\oauth\src\OAuth\OAuth1\Service\Flickr.php on line 52

Any thoughts on what could be causing this?

dependency issue upgrading to Symfony 6.2

Symfony 6.2 requires psr/cache ^2 or ^3 while phpflickr requires psr/cache ^1

Composer update snippets...
When upgrading from Symfony 5.4 to 6.2

    - symfony/cache[v6.2.0, ..., v6.2.4] require psr/cache ^2.0|^3.0 -> found psr/cache[2.0.0, 3.0.0] but it conflicts with your root composer.json require (^1).

When changing the requirement for psr/cache from ^1 -> ^3

    - samwilson/phpflickr[4.14.0, ..., 4.14.3] require psr/cache ^1.0 -> found psr/cache[1.0.0, 1.0.1] but it conflicts with your root composer.json require (3.*).

flickr-bundle for Symfony developers

I create a Symfony bundle that makes installing and using this library very easy.

https://github.com/survos/SurvosFlickrBundle

The README shows how to create a Symfony application by simply cutting and pasting from the command line. The hardest part is setting up the API Key and secret!

However, the demo simply shows one of my albums. What would be much more interesting is to integrate the auth, but I'm stuck on #66

In addition to putting the api key and secret in environment variables, there are 2 twig functions that make getting the thumbnail and the photo page easy. Note that if you embed the thumbnail in a webpage, you are required (by their terms of service) to provide a link to the photo page on Flickr.

   {% set url = flickrThumbnailUrl(photo) %}
        <figure class="figure">
            <a href="{{ flickrPageUrl(photo) }}" target="_blank">

No used composer

Hello,

I dont know and want used composer, so can I use this api for it to work?

Can i change:
require_once DIR . '/../vendor/autoload.php';
To
require_once DIR . '/../src/';

Thanks!

Help please, I have problems with sync_upload

Hello, first of all I appreciate your support. I have been trying to upload an image using Laravel 5.6, I have generated the accessToken and accessTokenSecret with the permission 'delete' and when I try it returns me "The Flickr API returned the following error: # 99 - Insufficient permissions Method requires write privileges; none . "
I really do not know what I'm doing wrong, I also call the getRecent method and it works without problems which makes me think that the authentication is also correct.

I leave my code:

image

Response:

image

I should also mention that I changed the 436 line of the PHPFlickr.php file:
image

by:
image

Because I was returning the following error:
image

I really hope you can help me, thank you very much, regards

Help with web-based authentication

I'm confused about how to set up the web-based authentication. Here's are my two controllers:

    #[Route('/flickr_login', name: 'flickr_login')]
    public function login(FlickrService $flickr): Response
    {
        $storage = new Session();
// Create the access token from the strings you acquired before.
        $token = new StdOAuth1Token();
// Add the token to the storage.
        $storage->storeAccessToken('Flickr', $token);

        $perm = 'read';
        $url = $flickr->getAuthUrl($perm, $this->urlGenerator->generate('app_flickr', [], UrlGeneratorInterface::ABSOLUTE_URL));

        return $this->render('flickr/index.html.twig', [
            'url' => $url,
        ]);
    }

    #[Route('/flickr', name: 'app_flickr')]
    public function index(Request $request, FlickrService $flickr): Response
    {
        $accessToken = $flickr->retrieveAccessToken($request->get('oauth_verifier'), $request->get('oauth_token'));
        $userId = $this->flickrService->test()->login();
    }

The oauth returns to the url correctly:

https://127.0.0.1:8000/flickr?oauth_token=72157720919697445-b0acefd2b8ba684f&oauth_verifier=b2bb64f7852464fe

It fails on retrieveAccessToken:

Warning: Undefined array key "oauth_token"

image

Any help would be appreciated.

Allow User-Agent to be set in the constructor

The user-agent default to the php library, but it might be better to be the calling application.

It'd be slightly easier to make that happen in the constructor rather than only via a separate call.

I can submit a PR.

If you do bump the minimum PHP version to only supported PHP, we can add types to many of the properties, too.

help please, photoset_getlist returns no photosets

I was using the original Dan Coulter library which worked for me, but is reporting errors on php7.2 so I installed this version via composer. However photoset_getlist returns no no photosets. No error, just 0 photosets. The old version returns the photosets I was expecting. Any suggestions please?

upload not setting privacy

 $params = [
            'title' => $title,
            'description' => $description,
            'tags' => $tags,
            'is_public' => false,
            'is_friend' => $isFriend,
            'is_family' => true,
            'content_type' => $contentType,
            'hidden' => $hidden,
        ];
        if ($async) {
            $params['async'] = 1;
        }
        dump($params);
        return $this->sendFile($photoFilename, $params);
    }

But when I upload the photo, the permissions are set to public:

https://www.flickr.com/photos/museado/53769410258/

image

Getting photos within sets

I've used this fork to replace the outdated version of phpFlickr that was coded into flogr (https://github.com/mcarruth/flogr) and it seems to work really well - thank you for all of the work that's gone into it.
The only problem I'm having is that some changes must have happened so long ago that I'm struggling to trace them back!

Is getting the photos within a particular set something I'd need an OAuth token for? I can currently get a list of my sets, and their cover photos - so I don't think the issue is with the API Key or API Secret...

Thanks

Session auth broken

I followed the example in examples/get_auth_token.php, and the web authentication failed after being redirected from Flickr with the query params. The page rendered as follows:


Warning: Undefined array key "oauth_token" in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/carlos-mg89/oauth/src/OAuth/OAuth1/Service/Flickr.php on line 68

Warning: Undefined array key "oauth_token_secret" in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/carlos-mg89/oauth/src/OAuth/OAuth1/Service/Flickr.php on line 69

Warning: Undefined array key "oauth_token" in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/carlos-mg89/oauth/src/OAuth/OAuth1/Service/Flickr.php on line 70

Warning: Undefined array key "oauth_token_secret" in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/carlos-mg89/oauth/src/OAuth/OAuth1/Service/Flickr.php on line 71
$accessToken = ""; $accessTokenSecret = "";
Fatal error: Uncaught Samwilson\PhpFlickr\FlickrException: Unable to decode Flickr response to flickr.test.login request: oauth_problem=token_rejected in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/samwilson/phpflickr/src/PhpFlickr.php:358 Stack trace: #0 /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/samwilson/phpflickr/src/TestApi.php(33): Samwilson\PhpFlickr\PhpFlickr->request('flickr.test.log...', Array, true) #1 /Users/clintonb/workspace/clintonb/wp-flickr-base/examples/get_auth_token.php(63): Samwilson\PhpFlickr\TestApi->login() #2 {main} thrown in /Users/clintonb/workspace/clintonb/wp-flickr-base/vendor/samwilson/phpflickr/src/PhpFlickr.php on line 358

Setproxy throws an uncaught error

Hey,

$f->setProxy("localhost", "8181"); is giving me a: Fatal error: Uncaught Error: Call to a member function setProxy() on null in /home/my/domain/public_html/FA/src/PhpFlickr.php:398

Any idea what this could be? I'm sure the proxy works.
Thanks

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.