How to download YouTube Thumbnail using PHP ?

YouTube has now become an integral part of our internet browsing habit. YouTube has provided easy access to the various sizes of video thumbnails.

The various resolutions of YouTube video thumbnails are provided below :

Thumbnail Links

  • Max Resolution : http://img.youtube.com/vi/youtube-video-id/maxresdefault.jpg
  • High Quality : http://img.youtube.com/vi/<youtube-video-id>/hqdefault.jpg
  • Medium Quality : http://img.youtube.com/vi/<youtube-video-id>/mqdefault.jpg
  • Standard Quality : http://img.youtube.com/vi/<youtube-video-id>/sddefault.jpg
  • Default Quality : http://img.youtube.com/vi/<youtube-video-id>/default.jpg
  • First Thumbnail : http://img.youtube.com/vi/<youtube-video-id>/0.jpg
  • Second Thumbnail : http://img.youtube.com/vi/<youtube-video-id>/1.jpg
  • Third Thumbnail : http://img.youtube.com/vi/<youtube-video-id>/2.jpg

Source Code :

<?php
function downloadThumbs($video_id) { 
    $path_to_save_thumbnails = 'thumbs/';
    $ch = curl_init();
    $thubnail_types = array(
                        'default',
                        'sddefault', 
                        'mqdefault',
                        'hqdefault', 
                        'maxresdefault',
                        '0',
                        '1',
                        '2'
                    );
    foreach($thubnail_types as $type) {
        $youtube_thumb_url = 'http://img.youtube.com/vi/'.$video_id.'/'.$type.'.jpg';
         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($info['http_code'] == 200) {
            file_put_contents($path_to_save_thumbnails.$type.'.jpg', $image);
        }
    }
    echo 'Success';
    curl_close($ch);
}

if(isset($_GET['id']) && $_GET['id']!=''){
    downloadThumbs($_GET['id']);
}else{
    echo 'id is missing';
}

Refer this video for complete guidance :



Recommended For You

About the Author: Admin