Validate YouTube Video


/ Published in: PHP
Save to your folder(s)

This function validates the URL of a YouTube video. It supports four kinds of URL: ?v=, /v/, #!v=, and the short version (youtu.be).

To validate the ID a request to YouTube is made, this is done using a personal class utilizing cURL.


Copy this code and paste it in your HTML
  1. public function isYoutubeVideo($value) {
  2. $isValid = false;
  3. //validate the url, see: http://snipplr.com/view/50618/
  4. if (isValidURL($value)) {
  5. //code adapted from Moridin: http://snipplr.com/view/19232/
  6. $idLength = 11;
  7. $idOffset = 3;
  8. $idStarts = strpos($value, "?v=");
  9. if ($idStarts === FALSE) {
  10. $idStarts = strpos($value, "&v=");
  11. }
  12. if ($idStarts === FALSE) {
  13. $idStarts = strpos($value, "/v/");
  14. }
  15. if ($idStarts === FALSE) {
  16. $idStarts = strpos($value, "#!v=");
  17. $idOffset = 4;
  18. }
  19. if ($idStarts === FALSE) {
  20. $idStarts = strpos($value, "youtu.be/");
  21. $idOffset = 9;
  22. }
  23. if ($idStarts !== FALSE) {
  24. //there is a videoID present, now validate it
  25. $videoID = substr($value, $idStarts + $idOffset, $idLength);
  26. $http = new HTTP("http://gdata.youtube.com");
  27. $result = $http->doRequest("/feeds/api/videos/".$videoID, "GET");
  28. //returns Array('headers' => Array(), 'body' => String);
  29. $code = $result['headers']['http_code'];
  30. //did the request return a http code of 2xx?
  31. if (substr($code, 0, 1) == 2) {
  32. $isValid = true;
  33. }
  34. }
  35. }
  36. return $isValid;
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.