Last updated on January 30, 2021
In this post, we gonna write a simple PHP script to grab the given website URL screenshot. So let’s create an HTML form to collect URLs from the user.
HTML Form
<form action="screenCaptureFromURL.php" method="post">
<p>Website URL: <input name="url" type="text" value=""></p>
<input name="submit" type="submit" value="Capture screen"></form>
We have just created a simple form with one field called URL and submit button. Submit button is to send the request to the server. The form action is pointed to screenCaptureFromURL.php, so let’s create screenCaptureFromURL.php
file.
PHP script to generate a screenshot for a given URL
We gonna use google APIs to grab the website screenshot and the code is commented pretty well, just through the comments for better understanding.
<?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.";
}
}