Skip to main content

This function is only working sometimes





function getYoutubeVideoId($url) {

$urlParts = parse_url($url);



if($urlParts === false)

return false;



if(isset($urlParts['host']) && strtolower($urlParts['host']) === 'youtu.be')

return ltrim($urlParts['path'], '/');



if(isset($urlParts['query'])) {

parse_str($urlParts['query'], $queryParts);



if(isset($queryParts['v']))

return $queryParts['v'];

}



return false;

}







This function works great.. unless you use youtu.be/* without http://





Why does it not work if it is just youtu.be or www.youtu.be ?


Comments

  1. Technically, youtu.be/foo is not a URL. A URL must have a scheme at the start, followed by ://.

    So the reason it isn't working is because you're giving the parse_url function invalid input. You must clean it up first.

    ReplyDelete
  2. Look what it returns for that input:

    php> =parse_url('youtu.be/id')
    array(
    "path" => "youtu.be/id",
    )


    Perhaps if host isn't set on the result, try re-parsing with http:// prepended.

    ReplyDelete
  3. I just use:

    function getYoutubeId($url){
    $parsed = parse_url($url);
    parse_str($parsed['query']);
    return $v;
    }


    Not sure if that helps...

    ReplyDelete
  4. The parse_url() function specifically does not validate the url, which is why your code would break.

    Try using preg_match() and a regex to validate the url first.

    ReplyDelete
  5. if(
    (isset($urlParts['host']) && strtolower($urlParts['host']) === 'youtu.be'))
    ||
    (!isset($urlParts['host'] && strstr($urlParts['path'],'/',true)=='youtu.be')

    ReplyDelete
  6. This seems to work:

    function getYoutubeVideoId($url) {
    $url = str_replace('http://', '', $url);
    $url = str_replace('www.', '', $url);
    $urlParts = parse_url($url);

    if($urlParts === false){
    return false;
    }

    if(strstr($urlParts['path'], 'youtu.be')){
    return str_replace('youtu.be/', '', $urlParts['path']);
    }

    if(isset($urlParts['query'])) {
    parse_str($urlParts['query'], $queryParts);

    if(isset($queryParts['v'])){
    return $queryParts['v'];
    }
    }

    return false;
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?