Advertisement
MrPauloeN

Verify whether a YouTube video exists using PHP and oEmbed

Jan 21st, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1.  
  2. /**
  3.      * Verify whether a YouTube video exists using PHP and oEmbed status codes 
  4.      * @author Ivan Melgrati
  5.      * @copyright 2018
  6.      */
  7.      
  8.     function YouTube_Check_ID($videoID)
  9.     {
  10.         $is_valid = true;
  11.         // YouTube oEmbed API endpoint (https://www.youtube.com/oembed)
  12.         // Query it using the video's URL as parameter
  13.         // The "format" parameter may be either JSON or XML. Not relevant for this tes.
  14.         $theURL = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$videoID&format=json";
  15.         $file_headers = @get_headers($url);
  16.         if ($file_headers === false)
  17.         {
  18.             $is_valid = false; // when server not found
  19.         }
  20.         else
  21.         {
  22.             foreach ($file_headers as $header)
  23.             {
  24.                 // Parse all headers. Corrects $url when 301/302 redirect(s) lead(s) to 200:
  25.                 if (preg_match("/^Location: (http.+)$/", $header, $m))
  26.                 {
  27.                     $url = $m[1];
  28.                 }
  29.                
  30.                 // Use regex to detect HTTP response codes
  31.                 if (preg_match("/^HTTP.+\s(\d\d\d)\s/", $header, $m))
  32.                 {
  33.                     $code = $m[1];
  34.                 }
  35.             }
  36.             // $code 404 This must be a bad video ID.
  37.             if ($code == 404) //
  38.             {
  39.                 $is_valid = false;
  40.             }
  41.         }
  42.         return $is_valid;
  43.     }
  44.  
  45. // https://www.youtube.com/watch?v=9fYhJzEqrns
  46.  
  47.     // $id = '9fYhJzEqrns'; //Video id goes here
  48.     // if (YouTube_Check_ID($id))
  49.     // {
  50.         // echo "Yes! The video exists";
  51.     // }
  52.     // else
  53.     // {
  54.         // echo "Oh, no! The video code is wrong and it can't be found on YouTube";
  55.     // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement