O'Reilly

Upload Photos to Flickr with PHP

By on  
Flickr PHP API

I have a bit of an obsession with uploading photos to different services thanks to Instagram. Instagram's iPhone app allows me to take photos and quickly filter them; once photo tinkering is complete, I can upload the photo to Instagram, Twitter, Facebook, and Flickr. This process made me wonder what it would take to upload photos to Flickr using PHP. This post details how you can authenticate and upload photos to Flickr using PHP with phpFlickr.

Step 1: Flickr Application Key Creation

Just as with every other API usage, you need to go to Flickr to sign up for an API key. Put together a good description and title, but one key is that you set the callback/redirect URL to the example page (or at least I did).

Step 2: Grab phpFlickr

phpFlickr is a suggested PHP library by Flickr. The library is not perfect (there seems to be a few long-standing redirect issues) but it does well as an all-purpose Flickr API interface.

Step 3: Configuring and Authentication

It's easiest to understand the process by looking at the code:

// Start the session since phpFlickr uses it but does not start it itself
session_start();

// Require the phpFlickr API
require_once('phpFlickr-3.1/phpFlickr.php');

// Create new phpFlickr object: new phpFlickr('[API Key]','[API Secret]')
$flickr = new phpFlickr('[API KEY]','[API SECRET]', true);

// Authenticate;  need the "IF" statement or an infinite redirect will occur
if(empty($_GET['frob'])) {
	$flickr->auth('write'); // redirects if none; write access to upload a photo
}
else {
	// Get the FROB token, refresh the page;  without a refresh, there will be "Invalid FROB" error
	$flickr->auth_getToken($_GET['frob']);
	header('Location: flickr.php');
	exit();
}

After starting the session and requiring the phpFlickr API library, an instance of phpFlickr needs to be created, providing it the API key and API secret. With the instance created, an if statement will be employed to react to a frob parameter from Flickr. If no frob is provided, the auth method should be called, which either confirms authentication or redirects the user to the Flickr site for sign in. If a frob is provided, the authentication token is set and the page needs to be refreshed (I'm not sure why the redirect needs to take place, but it was the only way to ensure authentication worked gracefully).

Step 4: Uploading a File

Uploading an image to Flickr is actually much easier with phpFlickr than authenticating. Uploading a file is as easy as one function call:

// Send an image sync_upload(photo, title, desc, tags)
// The returned value is an ID which represents the photo
$result = $flickr->sync_upload('logo.png', $_POST['title'], $_POST['description'], 'david walsh, php, mootools, dojo, javascript, css');

The sync_upload method allows many parameters, but the image, title, description, and tags are the most prominent. There is also an async_upload with may also be used.

phpFlickr also allows simple read access so that you may create a slideshow of photos, tags, etc., so don't think that phpFlickr is just for uploading!

My first attempt to create an independent PHP/Flickr script failed due to the need for OpenAuth. phpFlickr does a great job in managing the entire process, and the documentation is decent for getting started. I ran into a few problems with "too much redirection" (fixed by the "if" statement I added) and an "invalid frob" error (cured by the additional redirect) errors but beside those, phpFlickr is the right choice!

Track.js Error Reporting

Upcoming Events

Recent Features

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome,...

Incredible Demos

  • Assign Anchor IDs Using MooTools 1.2

    One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer's website, and on many customer websites. The best part about the plugin is that it's so easy to implement. I recently ran...

  • jQuery Chosen Plugin

    Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes...

Discussion

  1. Excellent, thanks for the example, i was looking for this php code for a long time.

  2. David I’m a newbie with PHP, and I was looking for this code for some time now. Thanks for the example.
    It’d be a great help if you could guide me trough the Authentication Flow.

    Thanks in advance :)

  3. Thanks, David. I was searching for something similar for a while.

  4. Phong Tran

    I have i TestWeb, it run on my local host Apache web server.
    I use this example and i run my web at URL “localhost/Flickr_API-sample/upload.php”
    I use right the key an secret that id received from my Flicker Account.

    I get an error “Oops! Flickr can’t find a valid callback URL.
    An external application has requested your login credentials and permission to perform certain actions on your behalf, but has failed to include all the required data.

    You don’t really need to know what this means, except that you can’t use the application until this problem is fixed. (It’s a third-party problem, not a Flickr problem.)

    There are lots of applications using the Flickr API. If you are curious about this, visit the Flickr Services page to see more examples of cool stuff. Otherwise, you might like to head to your home page…”

    Please help me for this problem.
    Thank very much.

    • Hey you need to set a callback url that is in the authentication flow in the edit app from where you created the app..

  5. Not clear tutorial.
    You have not given the content of all the related files..
    Blankly you have given the upload code without any connection with the authorization..

  6. What is the content of flickr.php??

  7. Jai

    What does this bit mean? $flickr->

    I am getting error unexpected “&”

  8. Carlos

    Very good.

    Muchas Gracias David…..

    Script genial y facil de entender.

  9. Can you provide me a code of .net to upload files to flickr and return the picture id?

  10. The Flickr API returned the following error: #95 – SSL is required

    I’m also getting same Error. when uploading Images

  11. Tuyen Pham

    May be upload images not sign in yahoo account?
    I am looking solution for it.
    And upload via URL?

  12. Tuyen Pham

    You server not support SSL or Socket

  13. Albar

    i get this error when trying to upload
    The Flickr API returned the following error: #98 – Invalid auth token

    is there anything i miss ??

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â New York

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...