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" />

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:

// apply validation check on url
   //website url
   $siteURL = $_POST['url'];
   //validate url 
   if(filter_var($siteURL, FILTER_VALIDATE_URL)){
   //Call Google PageSpeed Insights API
   //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."\" />";
    echo "Please enter a valid URL.";



Leave a Reply

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