I’ve been working on a small application that interfaces with the Flickr API in order to dynamically retrieve a stream of photos from a user’s Flickr feed.

In order to retrieve the stream, the user’s ID is required; however, most users are familiar with their Flickr username, not their ID. Services such as IDGettr can be a big help in looking up a user’s ID, but I wanted to roll something into the application that eliminated the need for a third-party service.

Assuming that you have a Flickr API Key, retrieving the user ID based on the username is easy enough.

First, I wrapped up my cURL calls into a function that I could call from anywhere in the codebase:

function curl($url) {

  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_USERAGENT, '');
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);

  $data = curl_exec($ch);
  if(curl_errno($ch) !== 0 || curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200):
    $data === false;

  return $data;


Assuming that you have access to the username, setup the URL to the Flickr API including the necessary query string variables. Specifically:

  • The method to retrieve the username (in this case flickr.people.findByUsername())
  • The API key
  • The username

From there, pass the URL of the Flickr API to the curl() function:

curl('http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=YOUR_API_KEY&username=' . $username);

From there, I grabbed the XML response from the simplexml_load_string() function because setting up an instance of the SimpleXMLElement was a little overkill for what I needed:

$xml = simplexml_load_string(curl('http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=YOUR_API_KEY&username=' . $username)));

I wrapped all of that into a function that ultimately returns the user’s ID from the XML response:

function get_flickr_user_id($username) {
  $xml= simplexml_load_string(curl('http://api.flickr.com/services/rest/?method=flickr.people.findByUsername&api_key=YOUR_API_KEY&username=' . $username));
  return $xml->user['id'];

Which is ultimately called form the markup in order to retrieve the photostream:

<div id="photostream">
  <script type="text/javascript" src="http://www.flickr.com/badge_code_v2.gne?count=10&amp;display=latest&amp;size=s&amp;layout=x&amp;source=user&amp;user=<?php echo get_flickr_user_id('the_username'); ?>"></script>

And done.