验证youtube api v3是否存在视频

时间:2015-03-20 12:22:01

标签: php api video youtube youtube-api

我正在尝试使用youtube api V3验证youtube视频(带有id_video)是否有效/存在。这就是我所做的(y2oy7b4SFgE是我测试的视频的ID):

$file_headers = @get_headers('https://www.googleapis.com/youtube/v3/videos?part=id&id=y2oy7b4SFgE&key=ma_clé_api_publique');
   //exit(var_dump($file_headers));
if ($file_headers[0] == 'HTTP/1.0 200 OK') {
  $resultat = $file_headers[0].'Goood'
} else {
  $resultat = $file_headers[0].'PasGoood'
}

但我有一个“代码”:403, “message”:“您的API密钥上配置了每IP或每个Referer限制,但请求与这些限制不符。如果来自此IP或referer的请求,请使用Google Developers Console更新您的API密钥配置被允许。“

没有参考时,它运作良好。但是,当我放一个,我尝试使用我的网站名称或我的vps服务器的IP,每次它都没有工作。

5 个答案:

答案 0 :(得分:24)

我知道有两种方法可以使用YouTube视频ID检查视频是否存在。

最简单的方法是使用oembed网址作为视频。这不需要身份验证,并在视频无效时返回404标头。你真的应该用curl来做这个,因为根据你的设置file_get_contents可能不适合你...

$headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $videoID);

if(is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false){
    // video exists
} else {
    // video does not exist
}

第二种是使用最近发布的V3 of the data api。要使用此方法,您需要在开发人员控制台中生成api密钥。

$response = file_get__contents('https://www.googleapis.com/youtube/v3/videos?part=id&id=' . $videoID . '&key=' . $apiPublicKey);
$json = json_decode($response);

if (sizeof($json['items'])) {
    // video exists
} else {
    // video does not exist
}

答案 1 :(得分:11)

在PHP中验证视频是否存在非常简单。 使用PHP函数file_get_contents检查是否存在视频。

general Video URL to check a video would be
$video_url = https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=VideoId

$video_url = @file_get_contents('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=Xu4MTv5wgys');
if($video_url) {
    echo('video exists');
} else {

    echo('video does not exists');

};

答案 2 :(得分:0)

您找到了解决方案吗?

官方方式是使用videos.list并提交视频ID。该文档提到了以下错误,但它从未抛出:

" notFound(404)videoNotFound找不到您要检索的视频。检查请求的id参数的值,以确保它是正确的。"

https://developers.google.com/youtube/v3/docs/videos/list?hl=de

答案 3 :(得分:0)

这是我的解决方案。在您向API发出请求之前,您必须从Google开发者控制台生成服务器密钥。

MyCustomClass temp = new MyCustomClass();
Field[] methods = temp.getFields();

答案 4 :(得分:-1)

我忘记了。这是我发现的解决方案,并认为这是最好的方式来谷歌喜欢控制所有。你必须在谷歌控制台中创建一个公钥,就像谷歌知道你的网站要求他验证一个视频,他可以很好地收取你的一些配额。

我执行以下操作并验证标题代码:

$file_headers = @get_headers('https://www.googleapis.com/youtube/v3/videos?part=id&id='. $id_video .'&key='.$publicKey);

if ($file_headers[0] == 'HTTP/1.0 200 OK') {
    $datavideo = file_get_contents('https://www.googleapis.com/youtube/v3/videos?part=id&id='. $id_video .'&key='. $publicKey);
    $data = json_decode($datavideo);
    if ($data->items)
        $this->idvideo = $id_video;
    else
        ...

} else {
    ...
}

希望它有助于我拥有声誉:D