How to download YouTube video thumbnails using PHP

The following post shows how you can retrieve any YouTube video thumbnails in PHP without using the YouTube api. I needed this for a onetime solution to get some thumbnails for a few videos and using the api seemed a little time consuming. So here goes.

YouTube video thumbnail structure

The urls from where you can get the thumbnails are shown below. Each video generates around 4 standard thumbnails. The first image is a full size image while others are smaller thumbnail images. You can easily try the following urls in the browser by replacing the ‘youtube-video-id’ part with the corresponding videos id.
# Default thumbnail

The id is the last part of the YouTube url or the id in the ‘v’ GET variable.

# Example, the id here is 'VSB4wGIdDwo'

Other than the above mentioned urls there are a few specific ones listed below which are also available.

Standard quality version:
Medium quality version:
High quality version:
Maximum quality version:

Note: Not all image types may be available for a video.

Getting images using PHP

Below is the PHP code to download thumbnails when given the video id.

// Set YouTube video id here
$video_id = 'VSB4wGIdDwo';
// Set path where to store thumbnails,
// Set this to a blank string to save in the current direcrory.
$path_to_save_thumbnails = 'E:/localhost/test/youtube-thumbs/';
// Nothing to change below this
$ch = curl_init();
// Thumbnail types
$thubnail_types = array('0', '1', '2', '3','default',
                      'sddefault', 'mqdefault',
                      'hqdefault', 'maxresdefault');
foreach($thubnail_types as $type) 
    $youtube_thumb_url = ''.$video_id.'/'.$type.'.jpg';
    echo "Downloading thumbnail [$type]." . PHP_EOL;
    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $youtube_thumb_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $image = curl_exec($ch);
    $info = curl_getinfo($ch);
    // If image is found than save it to a file.
    if($info['http_code'] == 200) {
        // Store thumbnails in the given directory, change this
        // to your liking.
        file_put_contents($path_to_save_thumbnails.$type.'.jpg', $image);
echo 'Done downloading.';
// close cURL resource, and free up system resources

2 thoughts on “How to download YouTube video thumbnails using PHP

  1. Thanks for the tip: nice to be able to get those images.

    If you know the URL you can use $image = file_get_contents($youtube_thumb_url); instead of CURL.

    If the URL is not valid/reachable, PHP issues a warning and $image is bool(false).

Comments are closed.