Social Media Link Preview using PHP


Social Medias today are one of the major source of traffic to web applications and websites. URL sharing in social media platforms like Facebook, Twitter, Instagram, Viber and others are used extensively to drive traffic to websites or other applications.

Merely sharing links won’t entice the users to click on it though. The use of thumb image, title and description will allow users to have a clear idea on what the link is all about and entice them to click on it and visit the destination page.

In this article, we are going to preview an URL with Facebook og meta tags using PHP.

Complete Source Code :

    display: flex;
    justify-content: center;
    width:460px;border:1px solid #ddd;background:#eee;padding:20px;
    width:500px;border:1px solid #ddd;background:#eee;cursor:pointer;
  .debug-box .text-wrapper{
  .debug-box .text-wrapper p strong{
    font-size: 1.4rem;
  .debug-box .text-wrapper .description{
  .debug-box img{
    max-height: 300px;
    display: block;
    width: 100%;
    height: calc(1.5em + .75rem + 2px);
    padding: .375rem .75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;

function getSiteOG( $url, $specificTags=0 ){
    $doc = new DOMDocument();
    $res['title'] = $doc->getElementsByTagName('title')->item(0)->nodeValue;

    foreach ($doc->getElementsByTagName('meta') as $m){
        $tag = $m->getAttribute('name') ?: $m->getAttribute('property');
        if(in_array($tag,['description','keywords']) || strpos($tag,'og:')===0) $res[str_replace('og:','',$tag)] = $m->getAttribute('content');
    return $specificTags? array_intersect_key( $res, array_flip($specificTags) ) : $res;

if(isset($_GET['url']) && $_GET['url']!=''){
  $url = $_GET['url'];
  if (filter_var($url, FILTER_VALIDATE_URL)) {
      $og_details = getSiteOG($url);
  } else {
      echo("Not a valid URL");


<div class="container">
  <div class="debug-form">
    <form action="" method="get">
      <input type="text" name="url" class="form-control">


  <?php if(isset($og_details) && $og_details){?>
    <div class="debug-box" onclick="openLink(this);" data-link="<?php echo $_GET['url'];?>">
      <img src="<?php echo @$og_details['image'];?>" width="100%">
      <div class="text-wrapper">
        <p><strong><?php echo @$og_details['title'];?></strong></p>
        <p class="description"><?php echo @$og_details['description'];?></p>
  <?php } ?>


  function openLink(source){
  function openInNewTab(url) {
    var win =, '_blank');

Follow this video for complete guidance :

ALSO READ  Basic Guidelines to Kanchanjunga Base Camp Trek

Comments are closed.