-
-
Save Kayakbabe/63507d65f6b7f2c97827749c3acddd77 to your computer and use it in GitHub Desktop.
Verify whether a YouTube video exists using PHP and oEmbed status codes. Instead of actually fetching the video’s URL using a tool suchas a cURL, we can speed things up by just checking the response headers by using PHP’s get_headers() function. Full article: https://imelgrat.me/json-xml/oembed-protocol-embed-videos-news/
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 | |
/** | |
* @author Ivan Melgrati | |
* @copyright 2018 | |
*/ | |
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