Facebook Like Preview Box in PHP | URL Preview Box

By | July 16, 2019
Facebook Like Preview Box

Facebook like preview box is very useful to get the information about the link we want to share. Recently i was working over a project and i was in need of this preview box. While thinking about this i remember i have created a script regarding the Facebook like preview box in PHP 5 or 6 Years back. I used that code made some changes and created a class of it. Now you can use it over your project you can download it from the bottom of the article. So let’s start that how i have created the class what functions are working over it and how we will get the URL Preview Box Result.

In this class i have used the image scroll. I use to try to get the whole images of the page then you can choose whatever suits you.

If you are working over the Localhost then “https” links will not work. They will work when you put the code over the server.




Things we collect in this class are

  • Title
  • Description
  • Keywords
  • Image
  • OgImage

Index.php

We use this page to create a form for taking the URL from the user. And a div to show the url elements. For processing the URL we use the Ajax to get the values.

<form>
        <div class="col-md-6 col-md-offset-3">
            <h2 class="text-center">URL Preview</h2>
    <div class="input-group">
        <input type="text" id="urlbox" class="form-control" placeholder="Search for...">
      <span class="input-group-btn">
          <button class="btn btn-primary" id="extract" name="extract" type="button">Extract</button>
      </span>
    </div>
        <br/>
        <i id="loader" class="fa fa-spin fa-spinner fa-2x"></i>
        <br/>
        <br/>
        <div id="bigbox">
            <div id="Title"></div>
        </div>
  </div>
    </form>

Above form will show the input box and a button over the page. Now we will put the Jquery which uses the click function for showing the result. Below function will show the loader icon then get the URL from the input box. Send the request to shareDetails.php for processing the url. We will send the URL as parameter for process. If our code returns the success and worked perfectly then it will hide the loading icon and parse the received Json and show the values in the Title box which is a part of bigbox.

<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script>
    $('#loader').hide();
    $('#extract').click(function(){
        $('#loader').show();
        var Url=$('#urlbox').val();
        $.ajax({
            type: "POST",
            url: "shareDetails.php",
            data:{url:Url},
            success: function(data){
                console.log(data);
                $('#loader').hide();
                var boxdata=$.parseJSON(data);
                $('#Title').html(boxdata.SharePrice);
            }
            });
    });
    </script>

Very small css to show everything perfectly.

<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
    <style>
        #Image img{display: none;}
        .active{display:block!important};
    </style>

As you can see we have setup the HTML page and everything is looking prefect. Now we will move to our main class functions which has created the magic behind the walls. We have created some functions so that we will get the perfect details.

shareDetails.php

This is our class which is having all the functions which will do the magic.

<?php
class urlPreviewDetails {
    
    private $dom="";
    public $websiteDetails=array();
    private $imageArr=array();
    
    public function __construct($url) {
        $this->initializeDom($url);
    }
    
    private function initializeDom($url){
        if($url!=""){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        $this->dom= new DOMDocument();
        @$this->dom->loadHTML($data);
        $this->websiteDetails["Url"]=$url;
        return $this->dom;
        }
        else
        {
            echo "Url is empty";
        }
    }
    
    function listWebsiteDetails(){
        $this->websiteDetails["Title"]=$this->getWebsiteTitle();
        $this->websiteDetails["Description"]=$this->getWebsiteDescription();
        $this->websiteDetails["Keywords"]=$this->getWebsiteKeyword();
        $this->websiteDetails["Image"]=$this->getWebsiteImages();
        return json_encode($this->websiteDetails);
    }
    
    function getWebsiteTitle(){
        $titleNode=$this->dom->getElementsByTagName("title");
        $titleValue=$titleNode->item(0)->nodeValue;
        return $titleValue;
    }
    
    function getWebsiteDescription(){
        $descriptionNode=$this->dom->getElementsByTagName("meta");
        for ($i=0; $i < $descriptionNode->length; $i++) {
             $descriptionItem=$descriptionNode->item($i);
             if($descriptionItem->getAttribute('name')=="description"){
                return $descriptionItem->getAttribute('content');
             }
        }
    }
    
    function getWebsiteKeyword(){
        $keywordNode=$this->dom->getElementsByTagName("meta");
        for ($i=0; $i < $keywordNode->length; $i++) {
             $keywordItem=$keywordNode->item($i);
             if($keywordItem->getAttribute('name')=="keywords"){
                return $keywordItem->getAttribute('content');
             }
        }
    }
    
    function getWebsiteImages(){
        $imageNode=$this->dom->getElementsByTagName("img");
        for ($i=0; $i < $imageNode->length; $i++) {
             $imageItem=$imageNode->item($i);
                $this->imageArr[].=$imageItem->getAttribute('src');
        }
        return $this->imageArr;
    }
    
    function getWebsiteOgImage(){
        $descriptionNode=$this->dom->getElementsByTagName("meta");
        for ($i=0; $i < $descriptionNode->length; $i++) {
             $descriptionItem=$descriptionNode->item($i);
             if($descriptionItem->getAttribute('property')=="og:image"){
                return $descriptionItem->getAttribute('content');
             }
        }
    }
}




initializeDom()

As the function name suggest that it will initialize the Dom and it takes URL as parameter. This url is the url which we will use to put in the input box. In this function we will create a CURL request and create an object of DOM. We will use the loadhtml function for getting the pagedetails. Our function will return the dom which is having whole details of the page.

getWebsiteTitle()

This function will take out the title of the website.

getWebsiteDescription()

This function will take the description the website. Which is available at the meta tag.

getWebsiteKeyword()

Keyword function will take out the keywords of the website.

getWebsiteImages()

It will take the whole images of the website. You can scroll the website images and you can use whichever you want.

getWebsiteOgImage()

Some of the websites dont use images but they use OgImage tag for showing the image at the time of sharing. So this function will take that URL.

Hope you like this tutorial if you have any issues please comment below. You can also download the files of this class.



2 thoughts on “Facebook Like Preview Box in PHP | URL Preview Box

  1. Muneeb Ahmad

    Sir It is not working even on my Server and also no error is displayed

    Reply
    1. Vivek Moyal Post author

      What error you are getting in your console.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *