2

How to know if youtube thumbnail with max resolution exists without using Google API?

For instance, video with code doesn't have maxresolution. If we open URL: http://i1.ytimg.com/vi/4rlR7EncGD0/maxresdefault.jpg we can see grey rectangle, that means no thumbnail, right?

The code I have, just checks if file exists. If file exists, it is showed within website. Unfourtunately this doesn't work for those "grey rectangles".

renathy
  • 5,125
  • 20
  • 85
  • 149

1 Answers1

4

I'am using this:

        $item = '4rlR7EncGD0';
        $MaxResURL = 'https://i1.ytimg.com/vi/'.$item.'/maxresdefault.jpg';
        //print $MaxResURL;

        $curl = curl_init();
        curl_setopt_array($curl, array(    
        CURLOPT_URL => $MaxResURL,
        CURLOPT_HEADER => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_NOBODY => true));

        $header = explode("\n", curl_exec($curl));
        curl_close($curl);

        //var_dump($header);        

        //If maxres image exists do something with it.
        if (strpos($header[0], '200') !== false) {    
            print $MaxResURL;
        }else{
            print 'Some Other IMG';
        }

This checks the headers using curl. And if it is good '200' prints the url, of course you can show the image or what you specifically need to do, I use this to add facebook and twitter metatags.

I used code from this answers:

How do I check if a string contains a specific word in PHP? To check for the 200 on the headers

And

PHP get_headers not working? To get the headers witch curl because I'm using wordpress and for some reason get_headers() was not working.

I'm not an expert and I do not know if this is the best aproach to resolve this issue but this code is working for me, hope it helps.

Community
  • 1
  • 1
Fernando
  • 41
  • 2