Skip to content

RESOURCES / BLOG

Capture Any Website Screenshot Using PHP

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

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

To see a working application demo, Click here Phpsandbox.

Entry-level html and php knowledge.

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 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.

      CLOUDINARY_NAME=
      CLOUDINARY_API_KEY=
      CLOUDINARY_API_SECRET=
      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

"index.php"


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Website screenshot</title>
 
    <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">
    <meta name="theme-color" content="#7952b3">
 
  </head>
  <body>
    
 
<div class="container py-3">
  <header>
    <div class="pricing-header p-3 pb-md-4 mx-auto text-center">
      <h3 class="display-4 fw-normal">Website screenshot and save to Cloudinary</h3>
    </div>
  </header>
 
  <main>
    <form >
        <div class="form-row">
            <div class="form-group col-md-4 offset-4">
                <label  class="sr-only">Site</label>
                <input type="text" class="form-control" name="site" placeholder="https://site.com">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-4 offset-4">
                <button type="submit" class="btn btn btn-dark">Capture shot</button>
            </div>
        </div>
    </form>
 
 
    <h2 class="display-6 text-center mb-4">Capture shot</h2>
 
    <div class="col">
        <?php if(isset($_GET['site'])){ ?>
            <!-- Display the ima using the screenshot url capture from response -->
            <img class="img-fluid" src="<?=$snap['data']?>" alt="snap">
        <?php }else { ?>
            <!-- If site is not yet set just provide message to enter site name -->
            <h2 class="text-muted text-center mb-4">Site name enter</h2>
        <?php  } ?>
    </div>
  </main>
 
</div>
  </body>
</html>
Code language: HTML, XML (xml)

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:

complete UI

Now to make the components function.

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.

      CLOUDINARY_NAME=
      CLOUDINARY_API_KEY=
      CLOUDINARY_API_SECRET=
      GOOGLE_API_KE=

Use autoload to load all the dependencies install with php composer

"index.php"


<?php
include_once __DIR__ . '/vendor/autoload.php';
use Cloudinary\Cloudinary;
use Cloudinary\Configuration\Configuration;
use Cloudinary\Api\Upload\UploadApi;
 
?>
 
Code language: PHP (php)

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

"index.php"

if(isset($_GET['site'])){
  
}
Code language: PHP (php)

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.

"index.php"

if(isset($_GET['site'])){
  $api =getenv("GOOGLE_API_KE");
    $site =$_GET['site'];
}
Code language: PHP (php)

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.

"index.php"

$adress="https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=$site&category=CATEGORY_UNSPECIFIED&strategy=DESKTOP&key=$api";
Code language: PHP (php)

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

"index.php"



$curl_init = curl_init($adress);
Code language: PHP (php)

Setup curls options for the get request

"index.php"

curl_setopt($curl_init,CURLOPT_RETURNTRANSFER,true);
Code language: PHP (php)

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

"index.php"


$response = curl_exec($curl_init);
Code language: PHP (php)

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

"index.php"

curl_close($curl_init);
Code language: PHP (php)

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

"index.php"

$googledata = json_decode($response,true);

Code language: PHP (php)

Extract image data from the decoded response to get.

"index.php"

$snapdata = $googledata["lighthouseResult"]["audits"]["full-page-screenshot"]["details"];
Code language: PHP (php)

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

"index.php"

$snap =$snapdata["screenshot"];
Code language: PHP (php)

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

 "index.php"

Configuration::instance([
		'cloud' => [
			'cloud_name' => getenv("CLOUDINARY_NAME"),
			'api_key' => getenv("CLOUDINARY_API_KEY"),
			'api_secret' => getenv("CLOUDINARY_API_SECRET")
		],
		'url' => [
			'secure' => true
		]
	]);
Code language: PHP (php)

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

 "index.php"

  	$response2 = (new UploadApi())->upload($snap['data'], [
		'resource_type' => 'image',
		]
	);
Code language: PHP (php)

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

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free