douju1928 2012-09-20 16:16
浏览 72

使用php验证youtube网址的问题

I'm trying to validate a youtube url taken from a form field. The way I have it setup isn't catching any error no matter what I put in. I use getVideoId() to extract the video id from the url which works.

    if ($_POST['video_url'] != null && $_POST['video_url'] != 'Youtube URL') {
        $vid_url = $_POST['video_url'];
        $video_id = getVideoId($vid_url);
        $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $video_id);
          if (strpos($headers[0], '200')) {
            $video_url = $vid_url;
          } else {
            $output .= 'This is not an existing youtube video<br/>';
          }
    }

The $output is set to null and I check against that before processing the form which works for how I validate other fields so it's just this method that is failing.

  • 写回答

3条回答 默认 最新

  • douzhe3516 2012-09-20 16:50
    关注

    If there is no valid video id, then $video_id is blank. If you try:

    $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/');
    echo $headers[0];
    

    you'll see that it returns a 200.

    $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/SOMETHINGINVALID');
    echo $headers[0];
    

    returns a 4xx of some description.

    You'll need to trap both cases:

    if ($_POST['video_url'] != null && $_POST['video_url'] != 'Youtube URL') {
        $vid_url = $_POST['video_url'];
        $video_id = getVideoId($vid_url);
        if ($video_id) {
            $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $video_id);
            if (strpos($headers[0], '200')) {
                $video_url = $vid_url;
              } else {
                  $output .= 'This is not an existing youtube video<br/>';
              }
        } else {
              $output .= 'This is not an existing youtube video<br/>';
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)