Туториали

Native PHP Bookmarks: Safe Link Previews with Real-Time Screenshot API Integration

Обележувачи во нативен PHP: безбедни прегледи на врски со интеграција на API за слики од екранот во реално време

A bookmark title tells you what you saved. A screenshot often tells you why. For a freelancer collecting design references or a small team tracking useful tools, visual previews make a modest bookmarks page much easier to scan.

The difficult part is drawing a trustworthy boundary around an untrusted URL. This Native PHP 8.3+ project keeps credentials on the server, restricts bookmark destinations, processes screenshots outside browser requests, and serves validated PNG files from private storage.

Get access and configure the service token

  1. Register an account or sign in.
  2. Open the Screenshot API service and plan page, choose the available Free, Plus, or Pro plan, and complete activation.
  3. Open the official documentation. Find the Service token panel and copy the service-scoped token.
  4. Store it in the project’s environment configuration below. Regenerating the token revokes the previous active token; coordinate replacement across running workers.

This service requires authentication. It accepts a Bearer token, an X-API-Token header, or a token query parameter. Use Bearer authentication here to keep credentials out of URLs.

The supplied contract is GET https://ai.mihajlo.mk/api/screenshot-api/v1/capture, with a required url query parameter and an image/png response body. A minimal request looks like this:

curl --fail --get \
  --connect-timeout 3 --max-time 20 \
  --header 'Authorization: Bearer YOUR_SERVICE_TOKEN' \
  --data-urlencode 'url=https://example.com/' \
  --dump-header preview.headers \
  --output preview.png \
  https://ai.mihajlo.mk/api/screenshot-api/v1/capture

The API supplies cached desktop or mobile screenshots without your maintaining Chromium infrastructure. This implementation uses the default capture behavior; it introduces no undocumented viewport parameters.

Keep the application small and the boundary explicit

Bookmarks enter through a CLI command. An authenticated, read-only web page displays them, while a scheduled worker creates previews. This avoids web mutation endpoints, CSRF handling, and browser requests that wait for rendering.

Install PHP 8.3+ with cURL, PDO SQLite, GD with PNG support, and Composer. Create this structure, keeping only public/ inside the document root:

bookmarks/
  .env
  .gitignore
  src.php
  bin.php
  public/index.php
  tests/CaptureTest.php
  var/

Create .env with these values:

SCREENSHOT_TOKEN='YOUR_SERVICE_TOKEN'
BOOKMARK_HOSTS='example.com,www.php.net'
BOOKMARK_USER='reader'
BOOKMARK_PASSWORD='REPLACE_WITH_A_LONG_RANDOM_PASSWORD'

The application reads process environment variables; PHP does not load this file automatically. For local commands, source this trusted shell-format file:

mkdir -p public tests var
chmod 700 var
chmod 600 .env
set -a
. ./.env
set +a
composer require --dev 'phpunit/phpunit:^11.0'

Add .env, var/, and vendor/ to .gitignore. Production should inject the same variables through its service configuration or secret manager.

Implement the HTTP boundary and domain outcomes

Save the following as src.php. The transport captures normalized response headers without assuming undocumented quota header names. The service maps HTTP responses into application states and validates image dimensions before decoding.

<?php
declare(strict_types=1);

function setting(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Missing configuration: $name");
    }
    return $value;
}

function database(): PDO {
    $db = new PDO('sqlite:' . __DIR__ . '/var/bookmarks.sqlite');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec('PRAGMA busy_timeout=5000');
    return $db;
}

function bookmarkUrl(string $url): string {
    $p = parse_url($url);
    $allowed = array_map('trim', explode(',', setting('BOOKMARK_HOSTS')));
    if (!filter_var($url, FILTER_VALIDATE_URL) || !$p ||
        ($p['scheme'] ?? '') !== 'https' ||
        !in_array(strtolower($p['host'] ?? ''), $allowed, true) ||
        array_intersect(['user', 'pass', 'port', 'query', 'fragment'],
            array_keys($p))) {
        throw new InvalidArgumentException('Use an approved public HTTPS URL.');
    }
    return $url;
}

final readonly class Reply {
    public function __construct(
        public int $status,
        public array $headers,
        public string $body
    ) {}
}

function curlCapture(string $endpoint, string $token): Reply {
    $body = '';
    $headers = [];
    $headerBytes = 0;
    $ch = curl_init($endpoint);
    if ($ch === false) {
        throw new RuntimeException('Cannot initialize cURL');
    }
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $token,
            'Accept: image/png',
        ],
        CURLOPT_CONNECTTIMEOUT => 3,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
        CURLOPT_HEADERFUNCTION => static function ($ch, string $line)
            use (&$headers, &$headerBytes): int {
            $headerBytes += strlen($line);
            if ($headerBytes > 32768) {
                return 0;
            }
            if (str_starts_with($line, 'HTTP/')) {
                $headers = [];
            } elseif (str_contains($line, ':')) {
                [$name, $value] = explode(':', $line, 2);
                $headers[strtolower(trim($name))] = trim($value);
            }
            return strlen($line);
        },
        CURLOPT_WRITEFUNCTION => static function ($ch, string $chunk)
            use (&$body): int {
            if (strlen($body) + strlen($chunk) > 5 * 1024 * 1024) {
                return 0;
            }
            $body .= $chunk;
            return strlen($chunk);
        },
    ]);
    try {
        $ok = curl_exec($ch);
        return new Reply(
            $ok === false ? 0 : (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE),
            $headers,
            $body
        );
    } finally {
        curl_close($ch);
    }
}

final readonly class Outcome {
    public function __construct(
        public string $state,
        public ?string $png,
        public array $headers
    ) {}
}

final class Screenshot {
    public function __construct(
        private string $token,
        private Closure $transport
    ) {}

    public function capture(string $url): Outcome {
        $endpoint = 'https://ai.mihajlo.mk/api/screenshot-api/v1/capture?'
            . http_build_query(['url' => $url], '', '&', PHP_QUERY_RFC3986);
        $r = ($this->transport)($endpoint, $this->token);
        $state = match (true) {
            $r->status === 0 => 'transport',
            $r->status === 429 => 'rate_limited',
            in_array($r->status, [500, 502, 503, 504], true) => 'upstream',
            in_array($r->status, [401, 403], true) => 'authentication',
            $r->status !== 200 => 'rejected',
            default => 'ready',
        };
        if ($state !== 'ready') {
            return new Outcome($state, null, $r->headers);
        }
        $type = strtolower(trim(explode(';',
            $r->headers['content-type'] ?? '')[0]));
        $size = @getimagesizefromstring($r->body);
        if ($type !== 'image/png' || !$size ||
            $size[2] !== IMAGETYPE_PNG ||
            $size[0] > 4096 || $size[1] > 4096 ||
            $size[0] * $size[1] > 8000000) {
            return new Outcome('invalid_image', null, $r->headers);
        }
        if (str_contains(strtolower(
            $r->headers['cache-control'] ?? ''), 'no-store')) {
            return new Outcome('storage_forbidden', null, $r->headers);
        }
        $image = @imagecreatefromstring($r->body);
        if (!$image) {
            return new Outcome('invalid_image', null, $r->headers);
        }
        ob_start();
        imagepng($image);
        $png = ob_get_clean();
        imagedestroy($image);
        return new Outcome('ready', $png, $r->headers);
    }
}

Re-encoding strips ancillary PNG content. Resource limits still matter: run workers with an appropriate PHP memory limit and process supervisor. Oversized transfers become bounded transport failures; invalid images never become browser responses.

Persist bookmarks and schedule bounded retries

Create bin.php. SQLite stores workflow state and private response metadata. A process lock prevents overlapping workers on one host. Each invocation handles at most ten eligible bookmarks.

<?php
declare(strict_types=1);
require __DIR__ . '/src.php';

$db = database();
$command = $argv[1] ?? '';
if ($command === 'init') {
    $db->exec("CREATE TABLE IF NOT EXISTS bookmarks (
        id INTEGER PRIMARY KEY, url TEXT NOT NULL,
        state TEXT NOT NULL DEFAULT 'pending',
        attempts INTEGER NOT NULL DEFAULT 0,
        next_at INTEGER NOT NULL DEFAULT 0,
        headers TEXT NOT NULL DEFAULT '{}'
    )");
} elseif ($command === 'add') {
    $q = $db->prepare('INSERT INTO bookmarks(url) VALUES (?)');
    $q->execute([bookmarkUrl($argv[2] ?? '')]);
} elseif ($command === 'work') {
    $lock = fopen(__DIR__ . '/var/worker.lock', 'c');
    if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
        exit(0);
    }
    $api = new Screenshot(setting('SCREENSHOT_TOKEN'), curlCapture(...));
    $q = $db->prepare("SELECT * FROM bookmarks
        WHERE state='pending' AND attempts<3 AND next_at<=?
        ORDER BY id LIMIT 10");
    $q->execute([time()]);
    foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $id = (int) $row['id'];
        $attempt = (int) $row['attempts'] + 1;
        $db->prepare("UPDATE bookmarks SET state='interrupted',
            attempts=? WHERE id=?")->execute([$attempt, $id]);
        try {
            $result = $api->capture(bookmarkUrl($row['url']));
            $state = $result->state;
            $headers = $result->headers;
            $retry = $headers['retry-after'] ?? '';
            $delay = ctype_digit($retry)
                ? (float) $retry
                : max(0, (strtotime($retry) ?: time()) - time());
            $delay = max($delay, 30 * (2 ** ($attempt - 1))
                + random_int(0, 15));
            if (in_array($state, ['transport', 'rate_limited', 'upstream'],
                true) && $attempt < 3 && $delay <= 86400) {
                $state = 'pending';
            }
            if ($result->png !== null) {
                $path = __DIR__ . "/var/$id.png";
                if (file_put_contents("$path.part", $result->png)
                    !== strlen($result->png) ||
                    !rename("$path.part", $path)) {
                    throw new RuntimeException('Image storage failed');
                }
            }
            $db->prepare('UPDATE bookmarks
                SET state=?, next_at=?, headers=? WHERE id=?')
                ->execute([$state, time() + (int) min($delay, 86400),
                    json_encode($headers, JSON_THROW_ON_ERROR), $id]);
        } catch (Throwable) {
            $state = 'internal';
            $db->prepare('UPDATE bookmarks SET state=? WHERE id=?')
                ->execute([$state, $id]);
        }
        error_log(json_encode([
            'bookmark_id' => $id, 'attempt' => $attempt, 'state' => $state,
        ]));
    }
} else {
    throw new InvalidArgumentException('Use init, add URL, or work');
}

Authentication and validation failures receive no automatic retry. Temporary failures get three total attempts, exponential delay, and jitter. Standard Retry-After values take precedence when longer; waits beyond one day require operator attention. There is no sleeping worker consuming a process slot.

A crash leaves interrupted visible for investigation. After fixing its cause, explicitly reset that row’s state, attempts, and next execution time. Keeping recovery deliberate prevents endless paid requests.

Serve the private bookmarks page

Save this as public/index.php. Every request requires HTTP Basic authentication, including image requests. Deploy it only through HTTPS; the local server below binds to loopback.

<?php
declare(strict_types=1);
require dirname(__DIR__) . '/src.php';

header('Cache-Control: private, no-store');
header('X-Content-Type-Options: nosniff');
header("Content-Security-Policy: default-src 'none'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'");
if (!hash_equals(setting('BOOKMARK_USER'), $_SERVER['PHP_AUTH_USER'] ?? '') ||
    !hash_equals(setting('BOOKMARK_PASSWORD'), $_SERVER['PHP_AUTH_PW'] ?? '')) {
    header('WWW-Authenticate: Basic realm="Bookmarks"');
    http_response_code(401);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    header('Allow: GET');
    http_response_code(405);
    exit;
}
$db = database();
if (isset($_GET['image'])) {
    $id = filter_input(INPUT_GET, 'image', FILTER_VALIDATE_INT,
        ['options' => ['min_range' => 1]]);
    $q = $db->prepare("SELECT id FROM bookmarks WHERE id=? AND state='ready'");
    $q->execute([$id ?: 0]);
    $path = dirname(__DIR__) . "/var/" . ($id ?: 0) . '.png';
    if (!$q->fetchColumn() || !is_file($path)) {
        http_response_code(404);
        exit;
    }
    header('Content-Type: image/png');
    readfile($path);
    exit;
}
header('Content-Type: text/html; charset=utf-8');
function escape(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
echo '<h2>Saved bookmarks</h2>';
foreach ($db->query('SELECT * FROM bookmarks ORDER BY id DESC') as $row) {
    echo '<p><a rel="noreferrer noopener" href="' . escape($row['url'])
        . '">' . escape($row['url']) . '</a>: '
        . escape($row['state']) . '</p>';
    if ($row['state'] === 'ready') {
        echo '<p><img width="320" alt="Saved page preview" src="?image='
            . (int) $row['id'] . '"></p>';
    }
}

Test the boundary without external requests

PHPUnit 11 supports PHP 8.3. This deterministic fake tests request construction, authentication failure mapping, quota metadata preservation, and rejection of a misleading successful response.

<?php
// tests/CaptureTest.php
declare(strict_types=1);
require_once dirname(__DIR__) . '/src.php';

use PHPUnit\Framework\TestCase;

final class CaptureTest extends TestCase {
    public function testRequestAndAuthenticationFailure(): void {
        $fake = function (string $endpoint, string $token): Reply {
            self::assertSame(
                'https://ai.mihajlo.mk/api/screenshot-api/v1/capture?'
                . 'url=https%3A%2F%2Fexample.com%2F', $endpoint);
            self::assertSame('test-token', $token);
            return new Reply(401, [], '');
        };
        self::assertSame('authentication',
            (new Screenshot('test-token', $fake))
                ->capture('https://example.com/')->state);
    }

    public function testRateLimitMetadataSurvives(): void {
        $api = new Screenshot('test-token',
            fn() => new Reply(429, ['retry-after' => '120'], ''));
        $result = $api->capture('https://example.com/');
        self::assertSame('rate_limited', $result->state);
        self::assertSame('120', $result->headers['retry-after']);
    }

    public function testHtmlCannotBecomeAPreview(): void {
        $api = new Screenshot('test-token',
            fn() => new Reply(200, ['content-type' => 'image/png'],
                '<p>upstream error</p>'));
        self::assertSame('invalid_image',
            $api->capture('https://example.com/')->state);
    }
}

Deploy with clear security and operational limits

The exact hostname allowlist deliberately excludes credentials, custom ports, queries, and fragments. Approve only public destinations you control or trust. It does not establish renderer-side SSRF protection: redirects and DNS changes happen at the provider. Verify the provider’s network restrictions before accepting arbitrary customer URLs. Never submit signed links or private document URLs.

Response headers remain in private SQLite storage for cache and quota diagnostics. Consult the official documentation for actual quota header names and meanings; do not guess reset units. Provider caching can make a newly requested preview depict an older page. Local browser caching is disabled, and upstream no-store prevents persistence.

Deploy the web process and scheduled worker under the same restricted account. Grant write access only to var/, disable displayed PHP errors, configure HTTPS, and verify your server populates PHP’s Basic authentication variables. Schedule php bin.php work every minute with the required environment. This single-host design trades distributed processing for simple, inspectable operation.

Monitor pending age, terminal states, disk space, and worker exits. Logs contain identifiers and outcomes, never tokens, URLs, or response bodies. Repeated authentication failures usually require checking plan activation or token rotation; invalid images warrant inspecting content type and size limits.

Verify the complete flow

vendor/bin/phpunit tests
php bin.php init
php bin.php add https://example.com/
php bin.php work
php -S 127.0.0.1:8080 -t public
  • Open the local page, authenticate, and confirm the preview appears.
  • Confirm unauthenticated image requests return 401.
  • Confirm an unapproved hostname is rejected at insertion.
  • Check stored headers and structured worker outcomes without exposing credentials.
  • Verify production scheduling, HTTPS, private storage, and token replacement.

A useful preview system earns trust at its boundaries: which URLs enter, which failures retry, and which bytes reach the browser. Keep those boundaries explicit, and a small bookmarks application can stay small even when its screenshots come from a powerful external renderer.

Портрет на автор на блогот

Mihajlo

Јас сум Михајло - развивач поттикнат од љубопитност, дисциплина и постојаната желба да создадам нешто значајно. Споделувам увиди, упатства и бесплатни услуги за да им помогнам на другите да ја поедностават својата работа и да растат во постојано развивачкиот свет на софтверот и вештачката интелигенција.