Skip to content

Instantly share code, notes, and snippets.

@paboden
Last active April 13, 2022 18:11
Show Gist options
  • Select an option

  • Save paboden/97c8a95f1adc4386608dba371d7fbb4f to your computer and use it in GitHub Desktop.

Select an option

Save paboden/97c8a95f1adc4386608dba371d7fbb4f to your computer and use it in GitHub Desktop.
Drupal 8/9: Get vimeo or youtube ids for media
/**
* Extracts the vimeo id from a vimeo url.
*
* Returns false if the url is not recognized as a vimeo url.
*/
function get_vimeo_id($url) {
return preg_match('#(?:https?://)?(?:www.)?(?:player.)?vimeo.com/(?:[a-z]*/)*([0-9]{6,11})[?]?.*#', $url, $m) ? $m[1] : false;
}
/**
* Extracts the youtube id from a youtube url.
*
* Returns false if the url is not recognized as a youtube url.
*/
function get_youtube_id($url) {
$parts = parse_url($url);
if (isset($parts['host'])) {
$host = $parts['host'];
if (
false === strpos($host, 'youtube') &&
false === strpos($host, 'youtu.be')
) {
return false;
}
}
if (isset($parts['query'])) {
parse_str($parts['query'], $qs);
if (isset($qs['v'])) {
return $qs['v'];
}
else if (isset($qs['vi'])) {
return $qs['vi'];
}
}
if (isset($parts['path'])) {
$path = explode('/', trim($parts['path'], '/'));
return $path[count($path) - 1];
}
return false;
}
/**
* Gets the thumbnail url associated with an url from either:
*
* - youtube
* - vimeo
*
* Returns false if the url couldn't be identified.
*
* In the case of you tube, we can use the second parameter (format), which
* takes one of the following values:
* - small (returns the url for a small thumbnail)
* - medium (returns the url for a medium thumbnail)
*/
function get_video_thumbnail_by_url($url, $format = 'small') {
if (false !== ($id = get_vimeo_id($url))) {
$hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$id.php"));
/**
* thumbnail_small
* thumbnail_medium
* thumbnail_large
*/
return $hash[0]['thumbnail_large'];
}
elseif (false !== ($id = get_youtube_id($url))) {
/**
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
*
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
* http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
*/
if ('medium' === $format) {
return 'http://img.youtube.com/vi/' . $id . '/hqdefault.jpg';
}
return 'http://img.youtube.com/vi/' . $id . '/default.jpg';
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment