Website Screenshot Generator Using PHP and ScreenshotMachine API

Website Screenshot Generator Using PHP and ScreenshotMachine API

In the digital age, visual representation plays a crucial role in web development and digital marketing. Whether you need to capture website previews, generate thumbnails, or archive web pages, having a reliable screenshot tool is invaluable. This article explores how to create a simple yet effective Website Screenshot Generator using PHP and the ScreenshotMachine API.

Why Use a Website Screenshot Generator?

A website screenshot generator can serve multiple purposes, including:

  1. Previewing Websites – Helps in website analysis and user experience design.
  2. Generating Thumbnails – Useful for search engines, directories, and SEO purposes.
  3. Archiving Websites – Captures the current state of a web page for historical reference.
  4. Monitoring Changes – Helps businesses track website modifications over time.

Follow this video for complete guidance :

Full Source Code : ScreenshotMachine API with PHP

<?php

function getScreenshotUrl($websiteUrl) {
    $apiKey = "YOUR_API_KEY";  // Replace with your actual API key from screenshotmachine.com
    $dimension = "1024x768";
    $format = "png";
    $cacheLimit = "0"; // 0 = always get a fresh screenshot
    
    // Build the API URL
    $apiUrl = "https://api.screenshotmachine.com/?key=" . $apiKey . 
              "&url=" . urlencode($websiteUrl) . 
              "&dimension=" . $dimension . 
              "&format=" . $format .
              "&cacheLimit=" . $cacheLimit;
    
    return $apiUrl;
}

$websiteUrl = '';
$screenshotUrl = '';
$error = '';
$showResult = false;

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['website_url'])) {
    $websiteUrl = trim($_POST['website_url']);
    
    // Validate URL
    if (empty($websiteUrl)) {
        $error = "Please enter a website URL";
    } elseif (!preg_match('/^https?:\/\//i', $websiteUrl)) {
        $websiteUrl = "https://" . $websiteUrl;
    }
    
    if (empty($error)) {
        // Get screenshot URL
        $screenshotUrl = getScreenshotUrl($websiteUrl);
        $showResult = true;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website Screenshot Generator</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css">
    <style>
        body {
            padding-top: 2rem;
            padding-bottom: 2rem;
            background-color: #f8f9fa;
        }
        .card {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .screenshot-container {
            max-width: 100%;
            overflow: hidden;
            margin-top: 20px;
            text-align: center;
        }
        .screenshot-image {
            max-width: 100%;
            height: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .btn-primary {
            background-color: #4A6ED0;
        }
        .btn-success {
            background-color: #28a745;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3 class="card-title mb-0">Website Screenshot Generator</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                            <div class="mb-3">
                                <label for="website_url" class="form-label">Enter Website URL:</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="website_url" name="website_url" 
                                           placeholder="e.g., https://example.com" 
                                           value="<?php echo htmlspecialchars($websiteUrl); ?>" required>
                                    <button type="submit" class="btn btn-primary">Generate Screenshot</button>
                                </div>
                                <?php if (!empty($error)){ ?>
                                    <div class="text-danger mt-2"><?php echo $error; ?></div>
                                <?php } ?>
                            </div>
                        </form>
                        
                        <?php if ($showResult){ ?>
                        <div id="screenshot_section" class="mt-4">
                            <h4 class="mb-3">Screenshot Generated</h4>
                            <div class="screenshot-container">
                                <img id="screenshot_img" src="<?php echo $screenshotUrl; ?>" 
                                     class="screenshot-image" alt="Website Screenshot">
                            </div>
                            <div class="d-flex justify-content-center mt-3 gap-2">
                                <a href="<?php echo $screenshotUrl; ?>" 
                                   class="btn btn-success" 
                                   download="screenshot_<?php echo date('YmdHis'); ?>.png">
                                    Download Screenshot
                                </a>
                                <a href="<?php echo $screenshotUrl; ?>" 
                                   class="btn btn-primary" 
                                   target="_blank">
                                    View Full Size
                                </a>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</html>

 

Choosing the Right API

There are various APIs available for capturing website screenshots. ScreenshotMachine is one such API that provides a reliable, easy-to-use service with a free tier. It allows users to generate screenshots with minimal setup while offering advanced customization options.

Overview of the Project

The goal of this project is to develop a simple PHP-based website screenshot generator. The application will allow users to enter a URL, fetch the website’s screenshot via the ScreenshotMachine API, and provide options to view or download the image.

Key Features of the Screenshot Generator

  • User Input for URL – Accepts website URLs from users.
  • API Integration – Fetches website screenshots using ScreenshotMachine.
  • Error Handling – Ensures proper URL validation.
  • Responsive Design – Uses Bootstrap for a clean and responsive UI.
  • Download & View Options – Allows users to save or preview the screenshot.

How It Works

  1. The user enters a website URL.
  2. The system validates the URL and appends ‘https://’ if missing.
  3. A request is sent to the ScreenshotMachine API to generate a screenshot.
  4. The screenshot is displayed, and users can either download or view it in full size.
  5. Bootstrap styling ensures a professional and user-friendly interface.

Understanding the Workflow

1. Handling User Input

User input is accepted through an HTML form. The entered URL is sanitized and checked for validity before processing.

2. Constructing the API Request

The API request URL is dynamically generated based on the provided website URL, API key, image dimensions, format, and caching preferences.

3. Displaying the Screenshot

Once the API returns a valid screenshot, it is embedded in the web page, along with buttons for downloading and viewing.

4. Error Handling

The application checks for common input errors, such as empty fields or invalid URLs, and notifies users accordingly.

Enhancements and Customization

  • Adjustable Image Dimensions: Users can be given options to select different screenshot sizes.
  • Full-Page vs. Visible Section: The API allows capturing either the full page or just the visible portion.
  • Custom Styling: CSS modifications can enhance the UI experience.
  • Automatic Background Processing: Using cron jobs or AJAX, screenshots can be generated in the background for improved performance.

Security Considerations

  • Sanitization of User Input: Ensuring only valid URLs are processed.
  • Rate Limiting: Preventing API abuse by limiting the number of requests per user.
  • Secure API Key Storage: Keeping the API key hidden from the front-end by storing it in environment variables or a secure configuration file.

A website screenshot generator is a valuable tool for developers, designers, and marketers alike. By integrating the ScreenshotMachine API with PHP, we can create a simple yet powerful application that enhances productivity and improves website analysis. The flexibility of this approach allows for further expansion and customization to meet various user needs.

By following this guide, developers can quickly implement their own screenshot generator and explore additional features to improve its functionality and user experience.

Related Posts