Created
February 14, 2019 21:28
-
-
Save imelgrat/2909d981dea446f58789f03d1680bb82 to your computer and use it in GitHub Desktop.
The function fetches response headers from YouTube's oEmbed URL for a given video and crawls through thenm in order to find whether the video actually exists.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Find if a Youtube video exists. | |
* | |
* The function fetches response headers from YouTube's oEmbed URL for a given video | |
* and crawls through thenm in order to find whether the video actually exists. | |
* | |
* @link https://imelgrat.me/json-xml/oembed-protocol-embed-videos-news/ | |
* | |
* @param string $videoID The YouTube video ID to check for | |
* | |
* @return bool Returns true if the video exists or false if the video can't be found. | |
*/ | |
function YouTube_Check_ID($videoID) | |
{ | |
$is_valid = true; | |
// YouTube oEmbed API endpoint (https://www.youtube.com/oembed) | |
// Query it using the video's URL as parameter | |
// The "format" parameter may be either JSON or XML. Not relevant for this tes. | |
$theURL = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$videoID&format=json"; | |
$file_headers = @get_headers($url); | |
if ($file_headers === false) { | |
$is_valid = false; // when server not found | |
} else { | |
foreach ($file_headers as $header) { | |
// Parse all headers. Corrects $url when 301/302 redirect(s) lead(s) to 200: | |
if (preg_match("/^Location: (http.+)$/", $header, $m)) { | |
$url = $m[1]; | |
} | |
// Use regex to detect HTTP response codes | |
if (preg_match("/^HTTP.+\s(\d\d\d)\s/", $header, $m)) { | |
$code = $m[1]; | |
} | |
} | |
// $code 404 This must be a bad video ID. | |
if ($code == 404) // | |
{ | |
$is_valid = false; | |
} | |
} | |
return $is_valid; | |
} | |
$id = 'BKorP55Aqvg'; //Video id goes here | |
if (YouTube_Check_ID($id)) { | |
echo "Yes! The video exists"; | |
} else { | |
echo "Oh, no! The video code is wrong and it can't be found on YouTube"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment