youtubeyoutube-api

How to gracefully handle YouTube thumbnail broken images when videos are taken down?


Our site contains some lists of YouTube videos with their thumbnails linked to the movies themselves. We fetch the thumbnail URLs from the YouTube API, and hotlink to them in situ on YouTube's servers. So our image tags look like:

<img src="http://i.ytimg.com/vi/o6CHqSN7O-o/2.jpg" alt="" width="133" height="78" />

The problem is that sometimes a video gets removed -- and so does the thumbnail. We don't know when that might happen, and our thumbnails just turn into broken images. How can we handle this?

There are a number of solutions:

Our ideal solution would be to point the img src to a location on YouTube that would display a friendly "move removed" image when a movie goes down. However, that doesn't seem to exist.

Anyone else dealt with this? Thanks!


Solution

  • Request the thumbnail from YouTube on the server side, save it into a cache on your server, display cached image. That way, you'll still have the thumbnail on your server, even if the original is removed. The thumbnail will be only requested once for each video. PHP-like pseudo code:

    <?php
    $filename = $this->get_thumbnail_filename_from_url($url); // any way to map an image URL into a filename - e.g. strip everything except [a-zA-Z0-9] from URL
    if (!file_exists($cachedir . '/' . $filename)) {
       $filename = $this->get_image_from_web_save_to_cache($url,$cachedir); // makes a HTTP request to the URL, saves the returned image (if any) into cache
    }
    $filename = basename($filename);
    echo "<img src=\"/cache/$filename\">"; // display your cached thumbnail
    ?>
    

    One pitfall: if the thumbnail changes, your cached version stays the same; not a common issue with YT videos though. This is solvable by making the cache more intelligent - but you'll have to start storing metadata (age, max-age, ...) and deal with the HTTP caching headers. Caching pseudocode: