How to take screenshot of a website using PHP

While programming in PHP there are many situtations when you would need some ready made function. Screenshot of a website using PHP is used for various purposes in plugins and custom web applications. I recently did a project in which i had to get screenshots of a website using php with only URL of page given. Basically the project was to code a link directory where people can submit their website links and other important information. I had to automatically capture and save the screenshot somewhere at the server. Once the image was saved it had to be shown in the web page. It could have been done in different ways like, Ask user to capture and upload screenshot or let him upload this image somewhere else and show that from external Url. But the most convenient way for user was to get the screenshot fetched automatically in my desired format. When i searched for some ready made solutions, I was shocked to see there is no such function or library and i was literally searching on google again and again for the phrase “how to take  screenshot of a website using php”.Luckily i found Google PageSpeed Insights API that can be used to fetch and save the screenshots easily.

 

Code to take screenshot of a website using php

Here is what i developed using this amazing Api. You are free to use this code for your needs or redistribute it anywhere you want. But i would recommend you to read and understand the details to become a better programmer.

In this code i assume you have already created a form to POST the URL to call this function. This function is ready to accept the URL and return the link of directory where this image is saved. All you have to do is change the directory appropriately and make sure it is writable( If not created already otherwise it will create it).


public function getScreenShot($siteUrl) {

$googlePagespeedData = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$siteUrl&screenshot=true");

$data = json_decode($googlePagespeedData, true);

$screenshot = $data['screenshot']['data'];

$data = str_replace('_', '/', $screenshot);
$data = str_replace('-', '+', $data);
$base64img = str_replace('data:image/jpeg;base64,', '', $data);
$data = base64_decode($base64img);



$fileName = 'news' . rand(10, 30) . '.jpg';

$path =  '/directory/tmp/' . $fileName;

$directory = dirname($path);

$image = @imagecreatefromstring($data);

if (mkdir($directory) && is_writable($directory)) {
imagejpeg($image, $path, 90);

return $fileName;
} else {
return 0;
}
}

If you use this function within your php code it should return the name of directory where the screenshot is stored, That you can send back to your html for displaying that image. It is that simple and easy.

Explanation of Code to take screenshot of a website using php

I highly recommend you to read this explanation before you implement that solution. It can also help you to change this function as per your needs.

$googlePagespeedData = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$siteUrl&screenshot=true")

This is our call to the google page speed api to fetch our screenshot and return a JSON decoded response containing the file information.

$data = json_decode($googlePagespeedData, true);

$screenshot = $data[‘screenshot’][‘data’];

We need to decode the data and get information about the returned string that we are going to use for saving the fetched screenshot.

$data = str_replace('_', '/', $screenshot);
$data = str_replace('-', '+', $data);
$base64img = str_replace('data:image/jpeg;base64,', '', $data);
$data = base64_decode($base64img);

This code is used to remove special characters and prepare the exact format for usage. At the end we are decoding it so that this string can be used for creating the file. This is most important step to take screenshot of a website using php.

$fileName = 'news' . rand(10, 30) . '.jpg';
$path =  '/directory/tmp/' . $fileName';
$directory = dirname($path);
$image = @imagecreatefromstring($data);

Ok now we have the string that we can use to display the image in browser, But it is not wise decision to always call this function and display the image in browser, a short and easy way is to store it somewhere and return its path. This is where you will change your code. Set the correct filename and path. Look at the filename variable. I am using a random number with its name to avoid name conflicts. Also the directory name should be set appropriately. For creating the image i am using above mentioned directory. This is where you should make a change. At the end we are storing the image data in $image variable. It is that easy  to take screenshot of a website using php.

 

if (mkdir($directory) && is_writable($directory))  {
imagejpeg($image, $path, 90); return $fileName; }  else {
 return 0;
 }

These lines are used to create a directory at specified path. If it is already available it should be readable. Make sure to change the permissions if you are on a linux system.

The function returns the path of image created OR 0 if there was some error. You should be able to track the error and fix that in your case. By now the image should be created in your specified directory.

 

I am a freelance php programmer and web developer. If you have any issue in implementation of this function let me know in comments and i will try to help you. If you are a webmaster looking for someone to code this for you.Also i am a freelance xenforo developer and expert with custom addon development.

 

Comments

Leave a Reply

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

About Author

I am a Haseeb, a software Engineer and experienced freelance php developer.I work hard to establish great understanding with my clients and build trust by crafting amazing Web Applications that can help them succeed. I work with Bloggers, Board Admins and Start-ups of all type as a php programmer.

freelance web developer