To retrieve a YouTube video thumbnail using the YouTube Data API v3 in PHP, follow these steps:
1. Prerequisites
- A Google Cloud API Key .
- The YouTube Video ID (e.g.,
dQw4w9WgXcQ
fromhttps://youtu.be/dQw4w9WgXcQ
).
2. PHP Code Example
<?php
function getYouTubeThumbnail($videoId, $apiKey) {
// API endpoint URL
$apiUrl = "https://www.googleapis.com/youtube/v3/videos";
$params = [
'part' => 'snippet',
'id' => $videoId,
'key' => $apiKey
];
$url = $apiUrl . '?' . http_build_query($params);
// Fetch data using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Decode JSON response
$data = json_decode($response, true);
// Check for errors
if (isset($data['error'])) {
throw new Exception("API Error: " . $data['error']['message']);
}
if (empty($data['items'])) {
throw new Exception("Video not found or invalid ID.");
}
// Extract thumbnails
$thumbnails = $data['items'][0]['snippet']['thumbnails'];
// Return the highest resolution available (fallback to lower resolutions)
if (isset($thumbnails['maxres'])) {
return $thumbnails['maxres']['url'];
} elseif (isset($thumbnails['standard'])) {
return $thumbnails['standard']['url'];
} elseif (isset($thumbnails['high'])) {
return $thumbnails['high']['url'];
} else {
return $thumbnails['default']['url'];
}
}
// Usage
$apiKey = "YOUR_API_KEY";
$videoId = "dQw4w9WgXcQ"; // Replace with your video ID
try {
$thumbnailUrl = getYouTubeThumbnail($videoId, $apiKey);
echo "Thumbnail URL: " . $thumbnailUrl;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
3. Direct URL Fallback (No API Key)
If you don’t need metadata, use YouTube’s thumbnail URL pattern:
$videoId = "dQw4w9WgXcQ";
$thumbnailUrl = "https://img.youtube.com/vi/$videoId/maxresdefault.jpg";
Available Sizes:
default.jpg
(120×90)mqdefault.jpg
(320×180)hqdefault.jpg
(480×360)sddefault.jpg
(640×480)maxresdefault.jpg
(1280×720)
4. Key Notes
- API Key Security:
- Never expose your API key in client-side code. Use PHP server-side logic.
- Restrict the API key to your domain in Google Cloud Console.
- Error Handling:
- Handle exceptions for invalid video IDs, API quota limits, or network issues.
- Performance:
- Cache thumbnail URLs to reduce API calls (e.g., store in a database).
5. Common Errors & Fixes
Error | Solution |
---|---|
API key invalid | Regenerate the key in Google Cloud Console. |
Video not found | Verify the video ID and ensure the video is public. |
Quota exceeded | Monitor usage in Google Cloud Console. |
maxresdefault.jpg missing | Fall back to sddefault.jpg or hqdefault.jpg . |
Use this code to reliably fetch YouTube thumbnails in PHP!