Skip to content

Instantly share code, notes, and snippets.

@Ulv
Created June 4, 2014 10:46
Show Gist options
  • Save Ulv/118bac164a7be053c452 to your computer and use it in GitHub Desktop.
Save Ulv/118bac164a7be053c452 to your computer and use it in GitHub Desktop.
download and cache youtube video thumbnail
/*
* возвращает путь к локальному файлу - thumbnail'у видео с youtube
*/
$getYoutubeThumb = function ($videoUrl) {
/*
* скачивает в кэш thumbnail видео, возвращает полный путь к файлу
* Имя файла = md5(url)
*/
$downloadPic = function ($srcUrl, $getThumbUrl) {
return call_user_func(
function ($url) {
if (empty($url)) {
return null;
}
$cachedFile = function () use ($url) {
if (!file_exists(ROOT_DIR . 'cache/yt_thumbs/')) {
mkdir(ROOT_DIR . 'cache/yt_thumbs/');
}
return ROOT_DIR . 'cache/yt_thumbs/' . md5($url) . '.jpg';
};
if (!file_exists($cachedFile())) {
file_put_contents(
$cachedFile(),
file_get_contents($url)
);
}
return $cachedFile();
},
$getThumbUrl($srcUrl)
);
};
return $downloadPic($videoUrl, function ($url) {
/*
* возвращает ссылку на thumb видео
*/
if (!empty($url)
&& preg_match_all("#\/\/(www\.)?youtube.com\/embed\/(\w+)#", $url, $matches, PREG_SET_ORDER)
) {
$videoHash = array_shift($matches);
$videoHash = end($videoHash);
return "http://i3.ytimg.com/vi/$videoHash/default.jpg";
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment