问题
In one of my application I need to show a YouTube video. If user submits a video then I have to check if that video is alive in YouTube. If OK then I have to save the video id in my database and generate video in web page.
Is there any method for validating YouTube video ?
回答1:
Use this class to extract and validate youtube video. This works for YT urls like /embed/ , /v/ , ?v= /, youtu.be
class Youtube {
///// Put together by Sugato
////////// $video_id is the youtube video ID /////////////////////////
public $video_id = null;
///////// the Constructer ////////////////////////////////////////
public function __construct($url)
{
if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else {
$this->video_id = NULL;
}
}
/////////// validates if a youtube video actually exists //////////////
function validate()
{
if(empty($this->video_id))
{
return false;
}
else {
$curl = curl_init("http://gdata.youtube.com/feeds/api/videos/" . $this->video_id);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
$request = curl_getinfo($curl);
curl_close($curl);
$result = explode(";", $request["content_type"]);
if($result[0] == "application/atom+xml")
{
return true;
} else {
return false;
}
}
}
}
Call the class like this
$yt = new Youtube($your_video_link_here);
$exist = $yt->validate();
if($exist)
{
echo "Yaaaayyyyyy!";
} else
{
echo "nAAAAyyyy!!!";
}
回答2:
If the user is flat-out submitting a video, you would have to have something like a database which contains hashes for existing videos to compare it with (ex: the SHA checksum), then check if the hash is already present. As far as I know, Google/YouTube provide no such database for the public to use, but you could start your own for the videos that users submit through your service. There are other more advanced techniques you could use, but they would require access to all of the existing video files for analysis... which is not available.
As far as getting the video URL, when you upload a video to YouTube you can link to it or embed it in a webpage.
来源:https://stackoverflow.com/questions/9280753/get-a-video-link-from-youtube