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

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


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 :(
}

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.


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;
    }