faceboo video thumbnail

The code snippet can be used to fetch facebook video thumbnail from any kind of URL. So far facebook has verity of URL format for videos and media files which depends on various factors. If you open a video from a page it will show regular format, if it is opened from a referral or shared by your friend the URL format will be different.

So in case you are eager to develop an application which show facebook thumbnail without using facebook SDK, copy the following code and pass URL to the function or download from Gist. The snippet can be used in a loop or with mySQL database as well.

Demo

function get_thumb($url)
{
  $url = trim($url);
  if(substr($url, -1)=="/")
  {
    $url = substr($url, 0, -1);
  }
  $urls = [$url];
  $ids = [];
  foreach ($urls as $url) 
  {
    $tmp = explode('/', $url);
    if (strtolower($tmp[count($tmp) - 2] == 'videos')) {
        $ids[$url] = $tmp[count($tmp) - 1];
        continue;
    }
    
    parse_str(parse_url($url)['query'], $query);
    
    if (!empty($query['v']))
    {
        $ids[$url] = $query['v'];
    }
    if(substr($url, -1)=="r"){
        $ids[$url] = $tmp[6];
    }
    if(substr($url, -1)=="y"){
        $ids[$url] = $tmp[5];
    }
    
    if(substr($tmp["3"], 0, 1)=="v"){
        $matches = array();
        $t = preg_match('/=(.*?)\&/s', $tmp["3"], $matches);
        $ids[$url] = $matches[1];
    }
    if(strpos($tmp[3], "video") !== false & substr($tmp[3], -1)!="r")
    {
       $ids[$url] = str_replace("video.php?v=", "", $tmp[3]);
    }
  }
$imgurl = $ids[$url];
echo "https://graph.facebook.com/$imgurl/picture/";
}

Note: If you have any other URL format and facing issue in fetching ID, share with me in comments.

Comments

comments

Comments closed