Capture Screenshot of a Webpage from its URL in PHP

|
| By Webner

Generally, Google PageSpeed Insights API is used to measure the performance of a web page but you can also use Google PageSpeed Insights API to get a screenshot of the website from URL. In this post, we will show you how to capture a screenshot of the webpage using its URL with the help of Google PageSpeed Insights API and PHP. The following sample script takes a screenshot of the website from the URL and shows as an image.

To create web page snapshot, Google PageSpeed Insights API need to be called with the following params :

URL: specify the URL of the webpage.
screenshot: specify screenshot=true to retrieve the screenshot.

1.  Create a sample HTML form:

<form method=”post” action="getScreenshot.php" >
<p>Website URL: <input type="text" name="url" value="" /></p>
<input type="submit" name="submit" value="CAPTURE" />
</form>

In the above form we have one input field which accepts URL of the website. On form submit the site URL is submitted to the PHP script to get the screenshot of the webpage.

2.  PHP script (getScreenshot.php) to get the screenshot of the URL entered in the first step:

<?php
// apply validation check on url
if(!empty($_POST['url'])){
   //website url
   $siteURL = $_POST['url'];
   //validate url 
   if(filter_var($siteURL, FILTER_VALIDATE_URL)){
   //Call Google PageSpeed Insights API
   $googlePagespeedData=file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$siteURL&screenshot=true");
   //decode response json data
   $googlePagespeedData = json_decode($googlePagespeedData, true);
   //convert screenshot data to image code
   $screenshot = $googlePagespeedData['screenshot']['data'];
   $screenshot = str_replace(array('_','-'),array('/','+'),$screenshot
   //display screenshot image
   echo "<img src=\"data:image/jpeg;base64,".$screenshot."\" />";
    }
   else
    {
    echo "Please enter a valid URL.";
    }
}
?>

Example:

1

Leave a Reply

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