Clavem

Validate a license key in a self-hosted PHP app

Call POST /v1/licenses/validate with cURL, cache the result for a day, and store a back-off time so a 429, a 503 or an outage never becomes one request per page view. The buyer runs your code on their own server, so the check keeps honest customers honest and nothing more.

The buyer controls the server

A PHP product you sell for self-hosting runs on a machine you do not control. The buyer can read your source, edit the check and delete the call. No PHP technique prevents that, and encoders that try to hide the code tend to break on hosts the buyer picks.

What validation does give you is an honest signal: which installs belong to a paid, unexpired license, and a way to switch off updates or support for the rest. Put real value where the buyer cannot edit it, such as updates or a hosted service, and treat the check in your code as a speed bump.

One class, one request a day

This class needs PHP 7.4 or later and the cURL extension. It stores the license in a JSON file outside the web root. ClavemToken is the signature check from the offline verification guide, and activate() is in the device activation guide.

<?php
final class ClavemLicense
{
    private const BASE = 'https://clavem.io';
    private const CHECK_EVERY = 86400; // seconds between online checks while the license is valid

    private $productId;
    private $publicKey;
    private $file;

    /** $file: a JSON file outside the web root, for example /var/lib/inkwell/license.json */
    public function __construct(int $productId, string $publicKey, string $file)
    {
        $this->productId = $productId;
        $this->publicKey = $publicKey;
        $this->file = $file;
    }

    /** Returns 'licensed', 'invalid', 'needs-network' or 'unlicensed'. Cheap enough for every request. */
    public function check(): string
    {
        $saved = $this->load();
        if ($saved === null) {
            return 'unlicensed';
        }

        if (time() >= ($saved['next_check'] ?? 0) && $this->takeLock($lock)) {
            try {
                [$status, $reply, $retryAfter] = $this->post('validate', [
                    'license_key' => $saved['key'],
                    'instance_id' => $saved['instance_id'],
                ]);
                if ($status === 200 && isset($reply['token'])) {
                    // Keep the new token even when the license is not valid: offline, it then says so.
                    $saved['token'] = $reply['token'];
                    $saved['next_check'] = time() + (!empty($reply['valid']) ? self::CHECK_EVERY : 3600);
                    $this->save($saved);
                    return !empty($reply['valid']) ? 'licensed' : 'invalid';
                }
                if ($status === 404) {
                    @unlink($this->file); // unknown key, or this install was removed: ask for the key again
                    return 'invalid';
                }
                // No answer (no network, 429, 5xx): stay quiet until the server says it is ready.
                $saved['next_check'] = time() + max($retryAfter, 60);
                $this->save($saved);
            } finally {
                flock($lock, LOCK_UN);
                fclose($lock);
            }
        }

        $claims = ClavemToken::verify($saved['token'], $this->publicKey);
        return ClavemToken::isLicensed($claims, $this->productId) ? 'licensed' : 'needs-network';
    }

    /** One request per expired cache, not one per visitor: whoever gets the lock calls the API. */
    private function takeLock(&$lock): bool
    {
        $lock = fopen($this->file . '.lock', 'c');
        if ($lock !== false && flock($lock, LOCK_EX | LOCK_NB)) {
            return true;
        }
        if ($lock !== false) {
            fclose($lock);
        }
        return false;
    }

    /** @return array{0:int,1:array,2:int} status (0 for no answer), decoded body, Retry-After seconds */
    protected function post(string $action, array $body): array
    {
        $retryAfter = 0;
        $ch = curl_init(self::BASE . '/v1/licenses/' . $action);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($body),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'User-Agent: Inkwell/3.2'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_TIMEOUT => 8,
            CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
                if (stripos($line, 'retry-after:') === 0) {
                    $retryAfter = (int) trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        $raw = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $decoded = is_string($raw) ? json_decode($raw, true) : null;
        return [$status, is_array($decoded) ? $decoded : [], $retryAfter];
    }

    private function load(): ?array
    {
        $json = @file_get_contents($this->file);
        $data = $json === false ? null : json_decode($json, true);
        return is_array($data) ? $data : null;
    }

    /** Write to a temporary file and rename it, so a request never reads half a file. */
    private function save(array $data): void
    {
        $tmp = $this->file . '.' . bin2hex(random_bytes(4)) . '.tmp';
        file_put_contents($tmp, json_encode($data));
        chmod($tmp, 0600);
        rename($tmp, $this->file);
    }
}

What the API answers

The request below uses the public demo key. The response is captured from the live API, with the token shortened.

curl https://clavem.io/v1/licenses/validate -d license_key="S1GNE-TDEM0-7K4QX-9WZ2P-H5RB8"
{
  "valid": true,
  "error": null,
  "license_key": { "id": 1, "status": "active", "activation_limit": 3, "activation_usage": 1, "expires_at": null, "test_mode": false },
  "instance": null,
  "meta": { "product_id": 1, "product_name": "Inkwell", "customer_email": "ada@example.com" },
  "token": "sgt1.eyJ2IjoxLCJsaWQiOjEsInB…"
}

Adding an instance_id the license does not have returns 404 with "error": "instance_id not found.". A known key always answers 200, so read valid, not only the status.

What check() does with each outcome

Answer check() Next online check
200, valid: true licensed, token replaced in 24 hours
200, valid: false (expired or disabled) invalid, token replaced, key kept in 1 hour
404 (license_key or instance_id not found) invalid, file deleted ask for the key again
429, Retry-After: 60 stored token decides after at least 60 seconds
503, Retry-After: 5 stored token decides after 60 seconds, not 5
400, or no answer at all (status 0) stored token decides after 60 seconds

The 503 row differs from the header on purpose. Waiting five seconds in a long-running app is fine. In PHP, five seconds is five seconds of page views, each making its own request, so the floor is 60.

PHP traps

  • No memory between requests. Without next_check in the file, every page view calls the API. The limit is 60 requests per 60 seconds per license key, shared by all of a buyer’s installs, so a site with more than one uncached view a second would be refused.
  • Many requests at the same moment. When the cache expires, a busy site starts several requests at once. The flock call lets one of them make the API call while the rest use the stored token.
  • Shared hosting. The License API also limits each IP address to 120 requests per 60 seconds. Hosts that send many sites out through one address share that budget, which is another reason to cache.
  • No cURL. file_get_contents() with a stream context needs allow_url_fopen, which the PHP manual lists as changeable only in php.ini or the server configuration, so a shared host can switch it off. If you use it, set ignore_errors or PHP returns nothing for a 4xx. Guzzle and Symfony HttpClient pick a working transport for you.
  • Where the key lives. Keep the file outside the document root, give it mode 0600, and never log the key. In Laravel that is a path under storage/.
  • Cron. On a busy site, run check() from cron and let page requests read only the stored state. Hosts without cron can trigger it from the admin dashboard.

Doing this with Clavem

The License API takes JSON or form bodies and needs no secret: the license key is the credential, so nothing sensitive ships in your product. Each validate also records when that install was last seen. Every endpoint and field is in the API reference. Clavem has no PHP package; the code above is the whole integration.

Questions

Should a PHP app validate the license on every request?

No. Every request is a new process with no memory, so an uncached check means one API call per page view. Validate about once a day and keep the time of the next check in a file or the database.

What if the buyer's server cannot reach the internet?

The check falls back to the signed token stored by the last successful validation. It stays good until its refresh_by time, 14 days after it was issued. See the offline verification guide for the token code.

Sources

  1. PHP manual, filesystem configuration (allow_url_fopen is INI_SYSTEM; checked November 2026)