Capture Any Website Screenshot Using PHP

Eugene Musebe

Introduction

Screenshots let you capture exactly what you're seeing on your screen to share with others or reference later. This article will demonstrate how much can be achieved using PHP and also manipulate Cloudinary services with such a service

Github

You may also use Github to view the project's Github repo.

Phpsandbox

To see a working application demo, Click here Phpsandbox.

Prerequisites

Entry-level html and php knowledge.

Setting Up the Sample Project

Create a new folder: website2imgphp Inside the new folder's terminal use the command composer init. You need to have php and composer downloaded to your machine.

Follow the composer procedure which will help handle the necessary project dependencies. When asked to search for a package, search for Cloudinary

Cloudinary

Cloudinary refers to an end-to-end image and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery. Our app will use the media file online upload feature. To begin, click here to set up a new account or log in to an existing one. We use the environment keys from the user dashboard to integrate Cloudinary with our project. We will create a file named env and use the guide below to fill in the project configuration.

1CLOUDINARY_NAME=
2 CLOUDINARY_API_KEY=
3 CLOUDINARY_API_SECRET=
4 GOOGLE_API_KE=

Our app's home component will include 2 sections; html and php. Start by including the following in the index.php directory

1"index.php"
2
3
4<!doctype html>
5<html lang="en">
6 <head>
7 <meta charset="utf-8">
8 <meta name="viewport" content="width=device-width, initial-scale=1">
9 <title>Website screenshot</title>
10
11 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
12 <meta name="theme-color" content="#7952b3">
13
14 </head>
15 <body>
16
17
18<div class="container py-3">
19 <header>
20 <div class="pricing-header p-3 pb-md-4 mx-auto text-center">
21 <h3 class="display-4 fw-normal">Website screenshot and save to Cloudinary</h3>
22 </div>
23 </header>
24
25 <main>
26 <form >
27 <div class="form-row">
28 <div class="form-group col-md-4 offset-4">
29 <label class="sr-only">Site</label>
30 <input type="text" class="form-control" name="site" placeholder="https://site.com">
31 </div>
32 </div>
33 <div class="form-row">
34 <div class="form-group col-md-4 offset-4">
35 <button type="submit" class="btn btn btn-dark">Capture shot</button>
36 </div>
37 </div>
38 </form>
39
40
41 <h2 class="display-6 text-center mb-4">Capture shot</h2>
42
43 <div class="col">
44 <?php if(isset($_GET['site'])){ ?>
45 <!-- Display the ima using the screenshot url capture from response -->
46 <img class="img-fluid" src="<?=$snap['data']?>" alt="snap">
47 <?php }else { ?>
48 <!-- If site is not yet set just provide message to enter site name -->
49 <h2 class="text-muted text-center mb-4">Site name enter</h2>
50 <?php } ?>
51 </div>
52 </main>
53
54</div>
55 </body>
56</html>

The code above creates a webpage titled Website screenshot and also imports bootstrap for its css features. We want a user to be able to fill a form with any website URL and receive an image containing the contents of the webpage. The webpage should also be backed up using the cloudinary online feature. The UI looks like the below:

Now to make the components function.

Cloudinary

Cloudinary refers an end-to-end image- and video management solution for websites and mobile apps, covering everything from image and video uploads, storage, manipulations, optimizations to delivery. Our app will use the media file online upload feature. To begin, click here to set up a new account or log in to an existing one. We use the environment keys from the user dashboard to integrate Cloudinary with our project. We willCreate a file named env and use the guide below to fill in the project configuration.

1CLOUDINARY_NAME=
2 CLOUDINARY_API_KEY=
3 CLOUDINARY_API_SECRET=
4 GOOGLE_API_KE=

Use autoload to load all the dependencies install with php composer

1"index.php"
2
3
4<?php
5include_once __DIR__ . '/vendor/autoload.php';
6use Cloudinary\Cloudinary;
7use Cloudinary\Configuration\Configuration;
8use Cloudinary\Api\Upload\UploadApi;
9
10?>

Confirm that the get request has the required form variable filled.

1"index.php"
2
3if(isset($_GET['site'])){
4
5}

Use the following link to Generate the Google API key for website insights. Attache the api key to the environmental variable so as to use it in the future and ensure the security of the application secrets.

1"index.php"
2
3if(isset($_GET['site'])){
4 $api =getenv("GOOGLE_API_KE");
5 $site =$_GET['site'];
6}

Build url to send the request to capture the website details to google using the google api key together with the user input url for the site.

1"index.php"
2
3$adress="https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=$site&category=CATEGORY_UNSPECIFIED&strategy=DESKTOP&key=$api";

Initialize the curl request with the earlier generated url. In preparation for sending a get request to google with the site url.

1"index.php"
2
3
4
5$curl_init = curl_init($adress);

Setup curls options for the get request

1"index.php"
2
3curl_setopt($curl_init,CURLOPT_RETURNTRANSFER,true);

Execute the curl request and capture the curl response for extraction of the website details specifically the screenshot.

1"index.php"
2
3
4$response = curl_exec($curl_init);

It is always a good practice to close the curl channels to avoid hoarding server resources. after the response has been received.

1"index.php"
2
3curl_close($curl_init);

Decode the json response received into a key-value pair php array.

1"index.php"
2
3$googledata = json_decode($response,true);

Extract image data from the decoded response to get.

1"index.php"
2
3$snapdata = $googledata["lighthouseResult"]["audits"]["full-page-screenshot"]["details"];

Isolate the captured screenshot from the data extracted in the previous section.

1"index.php"
2
3$snap =$snapdata["screenshot"];

Initialize cloudinary instance globally across the application with secret keys from the env

1"index.php"
2
3Configuration::instance([
4 'cloud' => [
5 'cloud_name' => getenv("CLOUDINARY_NAME"),
6 'api_key' => getenv("CLOUDINARY_API_KEY"),
7 'api_secret' => getenv("CLOUDINARY_API_SECRET")
8 ],
9 'url' => [
10 'secure' => true
11 ]
12 ]);

upload the screenshot base64 data to cloudinary for storage and capture the response to display on UI

1"index.php"
2
3 $response2 = (new UploadApi())->upload($snap['data'], [
4 'resource_type' => 'image',
5 ]
6 );

Thats it! you are successfully able to capture images from a Web URL. enjoy the experience.

Eugene Musebe

Software Developer

I’m a full-stack software developer, content creator, and tech community builder based in Nairobi, Kenya. I am addicted to learning new technologies and loves working with like-minded people.