TMDB API PHP tutorial: a cURL client and a movie page
A TMDB API PHP client needs only the curl extension. This tutorial builds one function that calls the API, retries a 429 and caches replies for 6 hours, plus a movie page with poster, cast and IMDb score. It uses the TMDB v3 JSON shape against https://api.amodb.dev/3 and needs PHP 8.2 or newer.
The TMDB API works from PHP with the cURL extension alone: one function, amodb_get(), sends the call, retries a 429 and caches the reply in a file. It uses the TMDB v3 JSON shape and runs against amodb at https:/, so only the base URL and the key differ from TMDB. A page view costs 1 request when the cache is cold and 0 when it is warm.
What do you need to follow this tutorial?
You need PHP 8.2 or newer with the curl extension, an amodb key and about 20 minutes.
| You need | Details |
|---|---|
| PHP | 8.2 or newer, checked with php -v |
| Extension | curl, which php -m lists when it is loaded |
| Composer | Not needed, the code has no dependencies |
| API key | An amodb key: 32 lowercase hex characters, the same shape as a TMDB v3 key. Plans start at $5.19 a month and there is no free tier. |
| Base URL | https:/ (TMDB uses https:/) |
| Time | About 20 minutes |
| Result | Two files: amodb.php with the function and movie.php with the page |
Which calls does the page make, and what do they cost?
The page makes 1 call per view when the cache is cold, and that call counts as 1 request toward the 20, 40 or 120 requests per minute of your key.
| Call | Path | Cache | Cost in requests |
|---|---|---|---|
| Details with cast and ratings | GET / | 6 hours at the edge | 1 |
| Same URL again, inside the file TTL | Read from the amodb-cache folder | 6 hours by default | 0 |
| Poster image | https:/, loaded by the browser | 30 days | 0, no key needed |
The cache file name comes from the full URL, so each id and each language gets its own file. A reply served from the edge cache still counts as a request, but a file hit costs 0.
Step 1: Get an API key
Buy a plan on amodb pricing with your email, sign in with the 6 digit code amodb then emails you, copy the first key, which is shown once, and export it as AMODB_KEY before you start PHP.
There is no free tier, and the plans differ in requests per minute: 20, 40 or 120. Every plan has every TMDB v3 compatible endpoint, the OMDb compatible endpoint, images, 14 languages and the extensions. Only Pro+ adds the all in one endpoint GET /, which this page does not use. Card, Apple Pay and Google Pay payments are prepaid and do not renew automatically, and Patreon renews monthly until you cancel on Patreon.
The key is 32 lowercase hex characters, the same shape as a TMDB API key. Export it before you start PHP:
The code reads it with getenv('AMODB_KEY'). Under PHP-FPM, workers do not see your shell, so set env[AMODB_KEY] in the pool configuration instead.
export AMODB_KEY="YOUR_API_KEY"Step 2: Prepare the project
Make a project folder and check that PHP is 8.2 or higher and that the curl extension is loaded.
The first command should report 8.2 or higher. The second must print curl.
mkdir movie-page && cd movie-page
php -v
php -m | grep -i curlStep 3: Send the first request
Send a first request with cURL that sets four things: the URL, a timeout, the Authorization header and a status check.
In PHP 8 the handle frees itself, so there is no curl_close().
<?php
$ch = curl_init('https://api.amodb.dev/3/movie/550?language=en-US');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('AMODB_KEY')],
]);
$body = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_RESPONSE_CODE), PHP_EOL;Step 4: Wrap it in a function
Put the cURL setup in one function, amodb_, that builds the URL with http_build_query, sends the call and returns a decoded array.
Calling cURL from every page repeats the same setup. The movie page passes append_, so cast and scores arrive in the same request. Field details are on the movie details API page, and poster sizes are on the TMDB image URL page.
Step 5: Handle errors and rate limits
Make the function throw AmodbException for every failure, so the page can catch errors in one place.
The status decides what happens next:
| Status | What the function does |
|---|---|
| 401 | Throws at once. A bad or suspended key cannot be fixed by retrying. |
| 404 | Throws with the status_message, so the page can say the id is unknown. |
| 429 | Reads the Retry-After header, sleeps for that many seconds (1 to 30), then retries up to twice. |
| 5xx | Throws with the status code and message. |
| cURL error | Throws Network error with the text from curl_error(). |
The header arrives through CURLOPT_HEADERFUNCTION, a callback that cURL runs for each response header line. See error codes for the full code list and rate limits for the sliding 60 second window.
Step 6: Cache replies in files
Hash the final URL with sha1, look for a file with that name and return it when its modified time is newer than the TTL.
The edge keeps details for 6 hours. A local file saves the request itself, and a cache hit costs nothing from your limit. Ages add up, so a file that is 6 hours old can hold data that was already hours old at the edge. Lower the TTL if that matters. When there is no fresh file, the function fetches, writes the body with LOCK_EX and returns the data.
Step 7: The complete program
Save the function as amodb.php and the page as movie.php, then start the built-in server and open the page.
First comes amodb.php:
<?php
declare(strict_types=1);
const AMODB_BASE = 'https://api.amodb.dev/3';
final class AmodbException extends RuntimeException
{
}
function amodb_get(string $path, array $query = [], int $ttl = 21600): array
{
$key = getenv('AMODB_KEY');
if ($key === false || $key === '') {
throw new AmodbException('Set the AMODB_KEY environment variable.');
}
$url = AMODB_BASE . $path . ($query ? '?' . http_build_query($query) : '');
$dir = sys_get_temp_dir() . '/amodb-cache';
$file = $dir . '/' . sha1($url) . '.json';
if (is_file($file) && time() - filemtime($file) < $ttl) {
return json_decode((string) file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
}
for ($attempt = 1; $attempt <= 3; $attempt++) {
$retryAfter = 1;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key, 'Accept: application/json'],
CURLOPT_HEADERFUNCTION => static function ($handle, string $line) use (&$retryAfter): int {
if (stripos($line, 'retry-after:') === 0) {
$retryAfter = (int) trim(substr($line, 12));
}
return strlen($line);
},
]);
$body = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
if ($body === false) {
throw new AmodbException('Network error: ' . $error);
}
if ($status !== 429 || $attempt === 3) {
break;
}
sleep(max(1, min($retryAfter, 30)));
}
if ($status === 401) {
throw new AmodbException('401: the API key is invalid or suspended.');
}
if ($status !== 200) {
$detail = json_decode((string) $body, true)['status_message'] ?? 'no message';
throw new AmodbException("amodb returned $status: $detail");
}
if (!is_dir($dir)) {
mkdir($dir, 0775, true);
}
file_put_contents($file, $body, LOCK_EX);
return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}Then comes movie.php. Every value goes through htmlspecialchars before it reaches the HTML.
Start the built-in server with php -S localhost:8000 and open http:/. The poster URL points at the image host, which needs no key.
<?php
declare(strict_types=1);
require __DIR__ . '/amodb.php';
function h(?string $text): string
{
return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8');
}
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ?: 550;
$movie = null;
$error = null;
try {
$movie = amodb_get("/movie/$id", ['language' => 'en-US', 'append_to_response' => 'credits,ratings']);
} catch (AmodbException $e) {
http_response_code(502);
$error = $e->getMessage();
}
$imdb = $movie['ratings']['imdb'] ?? null;
$cast = $movie ? array_slice(array_column($movie['credits']['cast'], 'name'), 0, 3) : [];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= h($movie['title'] ?? 'Movie lookup') ?></title>
</head>
<body>
<?php if ($error !== null): ?>
<p>Could not load the movie: <?= h($error) ?></p>
<?php else: ?>
<h1><?= h($movie['title']) ?> (<?= h(substr((string) ($movie['release_date'] ?? ''), 0, 4)) ?>)</h1>
<?php if (!empty($movie['poster_path'])): ?>
<img src="https://img.amodb.dev/t/p/w342<?= h($movie['poster_path']) ?>" alt="Poster of <?= h($movie['title']) ?>" width="342">
<?php endif; ?>
<p><?= h($movie['overview'] ?? '') ?></p>
<p>Cast: <?= h(implode(', ', $cast)) ?></p>
<p>IMDb: <?= $imdb ? h((string) $imdb['value']) : 'not known' ?></p>
<?php endif; ?>
</body>
</html>How do I keep the movie page safe?
Validate the id, escape every output value and keep the key out of the web root.
The page reads id through filter_input with FILTER_VALIDATE_INT, so a request such as ?id=abc falls back to 550 and never reaches the API path. Every value from the API goes through h(), which calls htmlspecialchars with ENT_QUOTES and UTF-8, so a title that contains a quote or a tag cannot break the HTML. The poster src is escaped the same way. The key stays in the environment, and the cache folder sits in the system temp directory, outside the web root. The messages the function throws never contain the key, because it travels in a header and not in the URL. On a public site you can show a fixed message instead and log the status_message on the server.
How do I switch this code between TMDB and amodb?
Change the AMODB_BASE constant and the key, and keep the rest of the function.
TMDB uses https:/ and your TMDB key. amodb uses https:/ and an amodb key, sent as Authorization: Bearer or ?api_key=. TMDB returns its own user score as vote_average and vote_count, plus imdb_id. amodb adds a ratings object with IMDb, Kinopoisk, Metacritic, Rotten Tomatoes and TMDB scores, and each score can be null, which is why the page tests $movie['ratings']['imdb'] ?. The limits differ too: TMDB allows about 40 requests per second per IP and says that could change, while amodb counts 20, 40 or 120 requests per minute per account.
Is the TMDB API free to use on a PHP site?
The TMDB API is free on a PHP site only until the site earns money, and amodb has no free tier.
TMDB staff said on the TMDB forum (2026-10-15) that a project is commercial once it earns revenue from ads, in-app purchases, donations or subscriptions. A blog with ad units or a paid members area therefore counts. TMDB's commercial plan costs $149 a month for companies under $1M revenue (TMDB staff, 2026-03-31), and its API terms require the TMDB logo plus a not-endorsed notice. amodb starts at $5.19 a month, which is 3.5% of $149, charges nothing extra for commercial use and asks for no amodb logo or credit line. Third party credits still apply: credit JustWatch for where to watch data, and show the attribution credit wherever a text or image carries one. Compare the plans on amodb pricing, or read Is the TMDB API free? for the longer answer. Sources read 2026-10-19.
What should I build next?
- Move the cache from the temp folder to a directory you control, and delete files older than a day with a cron job.
- Add
language=ru-RUor another of the 14 languages and cache each language separately, which the URL hash already does. - Add
moodstoappend_to_responseand print the entry of$movie['moods']['results']with the highestavg. See the movie mood API. - Read the quickstart, compare this with the TMDB API in Go tutorial or the TMDB API in JavaScript tutorial, or browse all tutorials.