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!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today’s websites and devices become ever more varied, a plethora of responsive images...

  • 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...

Incredible Demos

  • Create a 2 Column Layout with Flexbox

    Flexbox was supposed to be the pot of gold at the long, long rainbow of insufficient CSS layout techniques.  And the only disappointment I've experienced with flexbox is that browser vendors took so long to implement it.  I can't also claim to have pushed flexbox's limits, but...

  • MooTools Link Fading

    We all know that we can set a different link color (among other properties) on the hover event, but why not show a little bit more dynamism by making the original color fade to the next? Using MooTools 1.2, you can achieve that effect. The MooTools...

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

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...