Guides / PHP

Generate dynamic OG images in PHP

Pages with custom social cards get measurably more clicks than a generic logo when shared on X, LinkedIn or Slack. Designing one image per blog post by hand doesn't scale — RasterKit renders them from an HTML template with {{variables}} you fill from PHP.

Design the card once (plain HTML/CSS — gradients, fonts, avatars), store it as a template, then request /v1/image with a title and author per page. Combine with signed URLs and your og:image tag can point directly at the API.

1. Get an API key

Sign up free (magic link, no card) — your key is shown right after sign-in. You get 100 renders/month free across screenshots, PDFs, and images.

2. Create a template, then render it

Store a template once (dashboard or POST /v1/templates) — HTML/CSS with {{variables}} — then render it with per-page values:

<?php
$ch = curl_init('https://rasterkit.com/v1/image');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_HTTPHEADER => [
        'x-api-key: ' . getenv('RASTERKIT_API_KEY'),
        'content-type: application/json',
    ],
    CURLOPT_POSTFIELDS => '{"template_id": "tpl_your_template", "variables": {"title": "Hello World", "author": "Paul"}}',
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 200) {
    throw new RuntimeException("Render failed: $status $body");
}
file_put_contents('og-image.png', $body);
echo "Saved og-image.png\n";

The response body is the file itself — no JSON envelope to unwrap, no second download request. Errors come back as JSON with a stable error code.

3. Tune the output

The OG Image API reference documents every parameter. The ones people reach for first:

Use cases

FAQ

What size should OG images be?

1200×630 (the default) renders crisply everywhere — X, Facebook, LinkedIn, Slack, iMessage. Use device_scale_factor: 2 for retina-sharp text.

Are variables safe against HTML injection?

Yes — {{variable}} values are HTML-escaped by default. Use triple braces {{{variable}}} only for trusted markup.

Can I use custom fonts?

Yes — load Google Fonts or any @font-face in your template; the engine waits for fonts to be ready before capturing.

Related guides

Get your free API key →