How do I check if a video exists on YouTube, using PHP?

What about using Youtube's API?
After all, that would mean using some official, which is less likely to change than going with parsing some HTML page.

For more information: YouTube APIs and Tools - Developer's Guide: PHP

The Retrieving a specific video entry seems quite interesting: if you send a request to an URL like this one:

http://gdata.youtube.com/feeds/api/videos/videoID

(replacing "videoID" by the ID of the video, of course – "GeppLPQtihA" in your example), you'll get some ATOM feed if the video is valid; and "Invalid id" if it's not


And, I insist: this way, you rely on a documented API, and not on some kind of behavior that exists today, but is not guaranteed.


Youtube has support for the oEmbed format.
Compared to the xml responsed provided by Pascal MARTIN, mine has only to download 600 bytes against 3800 bytes, making it faster and less bandwidth cosuming (only 1/6 of the size).

function yt_exists($videoID) {
    $theURL = "http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=$videoID&format=json";
    $headers = get_headers($theURL);

    return (substr($headers[0], 9, 3) !== "404");
}

$id = 'yyDUC1LUXSU'; //Video id goes here

if (yt_exists($id)) {
    //  Yep, video is still up and running :)
} else {
    //  These aren't the droids you're looking for :(
}

Here is the solution that I use to check if YouTube video exists using video id. This is C# code, but basically you can check if the thumbnail of the video exists, you will either get 200 or 404 which is very convenient.

    private async Task<bool> VideoExists(string id)
    {
        var httpClient = new HttpClient();
        var video = await httpClient.GetAsync($"https://img.youtube.com/vi/{id}/0.jpg");
        return video.IsSuccessStatusCode;
    }

Request the URLs with the HEAD method, like so:

HEAD /watch?v=p72I7g-RXpg HTTP/1.1
Host: www.youtube.com                         

HTTP/1.1 200 OK
[SNIP]


HEAD /watch?v=p72I7g-BOGUS HTTP/1.1
Host: www.youtube.com              

HTTP/1.1 303 See Other
[SNIP]
Location: http://www.youtube.com/index?ytsession=pXHSDn5Mgc78t2_s7AwyMvu_Tvxn6szTJFAbsYz8KifV-OP20gt7FShXtE4gNYS9Cb7Eh55SgoeFznYK616MmFrT3Cecfu8BcNJ7cs8B6YPddHQSQFT7fSIXFHd5FmQBk299p9_YFCrEBBwTgtYhzKL-jYKPp2zZaACNnDkeZxCr9JEoNEDXyqLvgbB1w8zgOjJacI4iIS6_QvIdmdmLXz7EhBSl92O-qHOG9Rf1HNux_xrcB_xCAz3P3_KbryeQk_9JSRFgCWWgfwWMM3SjrE74-vkSDm5jVRE3ZlUI6bHLgVb7rcIPcg

Tags:

Php

Youtube