How to Take Screenshot of Website from URL using PHP?

There are many third party APIs available to take screenshots of the website that are available for this website as well as for scripts that have been deleted from the website. But if you want to create your own script to get a screenshot from the URL, then you can easily do this by using the PHP and Google Google PageSpeed Insights API.

In this tutorial, we will show you how to capture a screenshot of a website from the URL using the Google PageSpeed Insights API and PHP.

Index.html

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

getScreenshot.php

<?php
if(!empty($_POST['url'])){
    //website url
    $siteURL = $_POST['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 json data
        $googlePagespeedData = json_decode($googlePagespeedData, true);
        //screenshot data
        $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.";
    }
}
?>