Capture Screenshot of Website from URL using PHP

Web page screenshot capture functionality is used for various purposes in the web application. Mostly, the website screenshot is used to display a preview of a web page. When website URLs are required to list on the web page, displaying website screenshots as a preview will provide a great user interface.

There are various third-party APIs are available to take screenshots of the website. If you wish to build your own script to get a screenshot from URL, you can do it easily using PHP and Google PageSpeed Insights API.

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 the URL. In this tutorial, we will explain how to capture a screenshot of the website from URL using PageSpeed Insights API and PHP.

The example script is designed to capture screenshots of the website or any online web pages with PHP.

Create Google API Key

An API key is required to authenticate with Google PageSpeed Insights API. You need to attach the API key to the URL of the Google PageSpeed Insights API.

Before getting started, follow the below steps to enable the PageSpeed Insights API library and create an API key.

  • Go to the Google Developers Console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the sidebar, select Library under the APIs & Services section.
    • Search for the PageSpeed Insights API service in the API list and select PageSpeed Insights API.
    • Click the ENABLE button to make the PageSpeed Insights API Library available.
  • In the sidebar, select Credentials under the APIs & Services section.
    • In the Credentials page, select Create credentials » API key.
    • The API key will be created and a dialog will appear with the newly created API key.

Copy the API key for later use in the script on Google PageSpeed Insights API request.

Get Screenshot of Website from URL

The following code snippet helps to take a screenshot of the website by the URL and display it as a snapshot preview image.

We will use Google PageSpeed Insights API to take screenshots of the website using PHP. The Google API key should be appended in the query parameter to all request URLs. Some of the required parameters are given below.

  • url – Specify the URL of the website.
  • screenshot – Set it to true to retrieve the screenshot data.
  • key – Your API key.
// Google API key 
$googleApiKey 'Your_API_KEY';

// Website url
$siteURL "https://www.codexworld.com/";

// Call Google PageSpeed Insights API
$googlePagespeedData file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=$siteURL&screenshot=true&key=$googleApiKey");

// Decode json data
$googlePagespeedData json_decode($googlePagespeedDatatrue);

// Retrieve screenshot image data
$screenshot_data $googlePagespeedData['lighthouseResult']['audits']['final-screenshot']['details']['data'];

// Display screenshot image
echo '<img src="'.$screenshot_data.'" />';

You can also save website screenshot as an image on the server with PHP.

  • Use PHP file_put_contents() function to create image file and write base64 data in it.
// Save screenshot as an image 
list($type$screenshot_data) = explode(';'$screenshot_data);
list(, 
$screenshot_data)      = explode(','$screenshot_data);
$screenshot_data base64_decode($screenshot_data);

$output_file 'images/output.png';
file_put_contents($output_file$screenshot_data);

Capture Website Screenshot from URL

In this example script, we will show how you can build a form to get website screenshot by the URL provided by the user and display the web page screenshot to the user.

HTML Form to Get URL Input:
The HTML form has one input field which accepts the URL of the website.

<form method="post" action="getScreenshot.php">
    <div class="form-group">
        <label>Website URL:</label>
        <input type="text" class="form-control" name="site_url" value="" required="">
    </div>
    <div class="form-group">
        <input type="submit" class="form-control btn-primary" name="submit" value="Capture Screenshot"/>
    </div>
</form>

On form submission, the input value is posted to the server-side script (getScreenshot.php) to handle the screenshot capture process with PHP.

Fetch and Save Screenshot with PHP (getScreenshot.php):
This server-side script handles the screenshot capture process with Google PageSpeed Insights API using PHP.

  • Validate input value to check whether the given URL is valid using PHP FILTER_VALIDATE_URL Filter.
  • Call the Google PageSpeed Insights API and fetch data with PHP file_get_contents() function.
  • Retrieve screenshot image data of the website using PHP.
  • Get domain name from website URL and use the domain as the output screenshot file name.
  • Save base64 data in a file and save the screenshot as an image using PHP file_put_contents() function.
<?php 

// Google API key
$googleApiKey 'AIzaSyAVYsI0pKADCpX7T6UuhHD0ql6l8cs3ZKA';

// If URL input is submitted
if(isset($_POST['site_url'])){
    
$site_url $_POST['site_url'];
    
    
$val_err '';
    if (
filter_var($site_urlFILTER_VALIDATE_URL) === false) {
        
$val_err 'Please enter a valid website URL.';
    }
    
    if(empty(
$val_err)){
        try{
            
// Call Google PageSpeed Insights API
            
$googlePagespeedData file_get_contents("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=$site_url&screenshot=true&key=$googleApiKey");
            
            
// Decode json data
            
$googlePagespeedData json_decode($googlePagespeedDatatrue);
            
            
// Retrieve screenshot image data
            
$screenshot $googlePagespeedData['lighthouseResult']['audits']['final-screenshot']['details']['data'];
            
            
// Get domain name from site URL
            
$pieces parse_url($site_url);
            
$domain = isset($pieces['host']) ? $pieces['host'] : '';
            if(
preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i'$domain$regs)){
                
$domain $regs['domain'];
            }
            
            
// Save screenshot as an image
            
$screenshot_data $screenshot;
            list(
$type$screenshot_data) = explode(';'$screenshot_data);
            list(, 
$screenshot_data)      = explode(','$screenshot_data);
            
$screenshot_data base64_decode($screenshot_data);
            
            
$file_name = !empty($domain)?$domain.'.png':'output.png';
            
$output_file 'screenshots/'.$file_name;
            
file_put_contents($output_file$screenshot_data);

            
$statusMsg 'Screenshot saved as '.$output_file;
        }catch(
Exception $e){
            
$statusMsg $e->getMessage();
        }
    }else{
        
$statusMsg $val_err;
    }
}

?>

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

11 Comments

  1. Nikita Solanki Said...
  2. Keith Boyle Said...
  3. David Said...
  4. Huckbit Said...
  5. Manisha Said...
  6. PHP Developer Said...
  7. Akshay Said...
  8. Gautam Said...
  9. Damith Said...
  10. Sagar Nandwani Said...
  11. Rajkishor Said...

Leave a reply

keyboard_double_arrow_up