screenshot using php

While programming in PHP, there are many situations where you might need a ready-made function. Capturing a screenshot of a website with PHP is one such task, often required in plugins and custom web applications.

Recently, I worked on a project where I needed to capture website screenshots using only the URL of the page. The project involved building a link directory where users could submit their website links along with other relevant information. I had to automatically capture and save a screenshot of each submitted website on the server. Once saved, the screenshot would then be displayed on the web page.

There were alternative approaches—such as asking users to upload a screenshot manually or letting them provide an external image URL. However, the most user-friendly solution was to automate the screenshot capture in my desired format.

When I looked for a ready-made PHP solution, I was surprised to find there wasn’t a native function or widely used library for this. I kept searching Google with queries like “how to take screenshots of a website using PHP.”

Fortunately, I discovered the Google PageSpeed Insights API, which can be used to fetch and save website screenshots with ease.

Code to take screenshot of a website using php

Here’s what I developed using this amazing API. You’re free to use this code for your own projects or redistribute it as you wish. However, I highly recommend taking the time to read through and understand the details—it’ll help you become a better programmer.

In this example, I assume you’ve already created a form that sends the URL via POST to trigger this function. The function accepts the URL and returns the path to the directory where the screenshot is saved.

All you need to do is update the directory path accordingly and ensure that the directory is writable. If it doesn’t already exist, the function will create it automatically.


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 will return the name of the directory where the screenshot is stored. You can then pass this back to your HTML to display the image. It’s that simple and easy.

Explanation of Code to take screenshot of a website using php

I highly recommend reading this explanation before implementing the solution. It will also help you customize the function to suit your specific needs.

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

This is our call to the Google PageSpeed API to fetch the screenshot and return a JSON-decoded response containing the image data:

$data = json_decode($googlePagespeedData, true);

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

We decode the response and extract the screenshot data, which we’ll use to save the captured image to our server.

$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 format the string properly for use. In the final step, we decode the string so it can be used to create the image file. This is one of the most important steps when capturing a website screenshot using PHP.

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

Now that we have the image string, we can use it to display the screenshot in the browser. However, it’s not efficient to call this function every time you want to display the image. A better approach is to save the image once and return its file path.

This is where you should modify your code—set the correct filename and directory path. Take a look at the $filename variable: I’m appending a random number to avoid filename conflicts. Make sure to set the directory path appropriately. I’m using the previously mentioned directory for storing the image.

In the end, the image data is stored in the $image variable. As you can see, taking website screenshots using PHP is simple and straightforward.

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

These lines are used to create a directory at the specified path. If the directory already exists, it should be readable. Make sure to adjust the permissions if you’re working 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 software consultant and experienced programmer. If you encounter any issues implementing this function, feel free to leave a comment I’ll do my best to help you.

If you’re a webmaster looking for someone to develop this functionality for you, get in touch, and I’ll assist you with the implementation.

Related Posts