In the present day, YouTube embed video is used on many websites. Many web project needs to implement a YouTube video gallery where YouTube video thumbnails are dynamically listed in the gallery. In this article, we’ll provide the short PHP snippet to get YouTube video thumbnail image URL using PHP.
This simple PHP script is very useful when you want to get the YouTube video thumbnail image URL dynamically based on the provided YouTube URL. Using this YouTube thumbnail URL, you can design the video gallery as per your project needs.
The following PHP code extracts the src
value from YouTube Embed Code and generates the video thumbnail image URL based on YouTube video ID.
$embedCode = '<iframe width="560" height="315" src="https://www.youtube.com/embed/dwJasig9Olw" frameborder="0" allowfullscreen></iframe>';
preg_match('/src="([^"]+)"/', $embedCode, $match);
// Extract video url from embed code
$videoURL = $match[1];
$urlArr = explode("/",$videoURL);
$urlArrNum = count($urlArr);
// YouTube video ID
$youtubeVideoId = $urlArr[$urlArrNum - 1];
// Generate youtube thumbnail url
$thumbURL = 'http://img.youtube.com/vi/'.$youtubeVideoId.'/0.jpg';
// Display thumbnail image
echo '<img src="'.$thumbURL.'"/>';
The following PHP code generates the video thumbnail image URL based on YouTube video ID.
// YouTube video url
$videoURL = 'https://youtu.be/dwJasig9Olw';
$urlArr = explode("/",$videoURL);
$urlArrNum = count($urlArr);
// Youtube video ID
$youtubeVideoId = $urlArr[$urlArrNum - 1];
// Generate youtube thumbnail url
$thumbURL = 'http://img.youtube.com/vi/'.$youtubeVideoId.'/0.jpg';
// Display thumbnail image
echo '<img src="'.$thumbURL.'"/>';
YouTube allow you to get the following thumbnail sizes.
http://img.youtube.com/vi/VideoID/0.jpg http://img.youtube.com/vi/VideoID/1.jpg http://img.youtube.com/vi/VideoID/2.jpg http://img.youtube.com/vi/VideoID/3.jpg
Also the different quality of thumbnails is available.
http://img.youtube.com/vi/VideoID/default.jpg http://img.youtube.com/vi/VideoID/hqdefault.jpg http://img.youtube.com/vi/VideoID/mqdefault.jpg http://img.youtube.com/vi/VideoID/sddefault.jpg
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thank you very helpful
Thanks man, this one is so readable. thumbs up!!!
Thank you so much you just saved me 😛
Thank you, very good!