Posted By

peckham on 07/27/11


Tagged

video validate YouTube


Versions (?)

Validate YouTube Video


 / Published in: PHP
 

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.

  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
Posted By: adrapok on September 18, 2012

And the HTTP Class?

Posted By: peckham on October 14, 2012

Sorry for my late response. The HTTP class is just a small basic wrapper around cURL which returns the response headers and the response body.

You need to login to post a comment.