tools/SDKs/PHP SDK

PHP SDK

Connect PHP applications to SikkerKey with a machine identity, then read, export, cache, and refresh permitted secrets.

Updated yesterday

The SikkerKey PHP SDK gives PHP applications secure, read-only access to secrets in your vault. Each client uses a machine identity, so the application can retrieve only the secrets and projects that machine is permitted to access.


#Requirements

  • PHP 8.1 or later

  • The sodium, curl, and json PHP extensions

  • The openssl extension when using encrypted fallback

  • A SikkerKey vault and machine identity

The SDK has no third-party Composer package dependencies. Calls are synchronous and fit naturally into PHP web requests, queue workers, scheduled commands, and command-line applications.


#Install the SDK

bash
composer require sikkerkey/sdk

#Read your first secret

php
<?php

require_once __DIR__ . '/vendor/autoload.php';

use SikkerKey\SikkerKey;

$sikkerKey = SikkerKey::create('vault_...');
$apiKey = $sikkerKey->getSecret('sk_...');

// Pass $apiKey directly to the client or service that needs it.

Do not echo secret values or include them in application logs.


#Choose a machine identity

Use a standard machine for persistent application hosts and workers. Use an ephemeral machine for short-lived workloads that should keep their identity only in memory.

Use a standard machine

php
// Select a registered vault.
$byVault = SikkerKey::create('vault_...');

// Load a specific identity file.
$byPath = SikkerKey::create(
    '/etc/sikkerkey/vaults/vault_.../identity.json'
);

// Use SIKKERKEY_IDENTITY or select the only registered vault.
$automatically = SikkerKey::create();

Automatic selection checks SIKKERKEY_IDENTITY first. If it is not set, the SDK selects the identity when exactly one vault is registered under ~/.sikkerkey/vaults/. Select a vault explicitly when several identities are available.

Set SIKKERKEY_HOME when the application uses a different protected identity directory:

bash
export SIKKERKEY_HOME=/var/lib/sikkerkey

Use an ephemeral machine

php
$sikkerKey = SikkerKey::bootstrapInMemory(
    getenv('SIKKERKEY_VAULT_ID'),
    getenv('SIKKERKEY_ENROLLMENT_TOKEN'),
    hostname: 'checkout-worker',
    name: 'Checkout worker',
);

$apiKey = $sikkerKey->getSecret('sk_...');

bootstrapInMemory generates an Ed25519 key pair in memory, registers the ephemeral machine, and returns a ready client. It writes no identity or private key to disk, and the private key disappears when the PHP process exits.

The machine follows the access, hostname rules, use limit, and lifetime configured on the enrollment token. The hostname defaults to HOSTNAME and then to serverless. A name pattern configured on the token takes precedence over the requested name.

Keep enrollment tokens in protected runtime configuration and set the machine lifetime and token use limit for the workload's duration and expected concurrency.


#Read secrets

Read a standard secret

php
$apiKey = $sikkerKey->getSecret('sk_...');

Read a structured secret

php
$database = $sikkerKey->getFields('sk_...');

$host = $database['host'];
$username = $database['username'];
$password = $database['password'];

Read one field directly with:

php
$password = $sikkerKey->getField(
    'sk_...',
    'password'
);

getFields returns an associative array. Scalar properties become strings, while nested values are returned as JSON text. A non-object value produces SecretStructureError; a missing field produces FieldNotFoundError with the available field names.


#Discover and export secrets

php
$secrets = $sikkerKey->listSecrets();
$projectSecrets = $sikkerKey->listSecretsByProject('proj_...');

foreach ($secrets as $secret) {
    echo "{$secret->id}: {$secret->name}\n";
}

Each SecretListItem includes the secret ID and name, with optional project and structured-field metadata. Listing returns metadata, not secret values.

Export application configuration

php
$allConfiguration = $sikkerKey->export();
$projectConfiguration = $sikkerKey->export('proj_...');

Export returns an array<string,string> in one request. Names use uppercase environment-variable format, and structured secrets are flattened into entries such as DATABASE_HOST and DATABASE_PASSWORD.

php
foreach ($projectConfiguration as $name => $value) {
    putenv("{$name}={$value}");
}

#Enable encrypted fallback

php
$sikkerKey = SikkerKey::create('vault_...')
    ->enableCache(
        maxAge: 3600,
        onFallback: static function (
            string $secretId,
            int $cachedAt
        ): void {
            error_log(
                "Using cached value for {$secretId} from epoch {$cachedAt}"
            );
        },
    );

Encrypted fallback is opt-in. Successful reads are encrypted locally with AES-256-GCM using a key derived from the machine identity and vault. maxAge is measured in seconds; pass null for no automatic expiry. onFallback runs only when the SDK serves a cached value.

Fallback is limited to network failures, timeouts, and temporary gateway or service availability responses. Authentication failures, denied access, missing secrets, rate limits, and other authoritative responses are returned to the application.

Cache entries are bound to the machine, vault, secret, and creation time. The format is compatible with SikkerKey CLI and the other SikkerKey SDKs. Use it with a persistent, protected identity directory.


#Refresh secrets on your schedule

Applications that periodically refresh configuration can call the read methods again on their own schedule. Each call returns the current value permitted for the machine.

php
$apiKey = $sikkerKey->getSecret('sk_...');

// In a worker or scheduled command, repeat the read at the interval
// appropriate for your application, then replace the in-memory client value.

#Work with vaults and inspect the client

php
$vaultIds = SikkerKey::listVaults();
$production = SikkerKey::create('vault_...');
$staging = SikkerKey::create('vault_...');

Create a separate client for each vault. The active identity is available as the read-only properties machineId, machineName, vaultId, and apiUrl, and through methods with the same names.


#Handle errors

php
use SikkerKey\AccessDeniedError;
use SikkerKey\ApiError;
use SikkerKey\AuthenticationError;
use SikkerKey\ConfigurationError;
use SikkerKey\NotFoundError;
use SikkerKey\RateLimitedError;

try {
    $value = $sikkerKey->getSecret('sk_...');
} catch (NotFoundError) {
    handleMissingSecret();
} catch (AccessDeniedError) {
    handleRemovedAccess();
} catch (AuthenticationError) {
    handleAuthenticationFailure();
} catch (RateLimitedError) {
    scheduleLaterRetry();
} catch (ApiError $error) {
    recordServiceError($error->httpStatus);
} catch (ConfigurationError) {
    handleIdentityConfiguration();
}

All SDK errors extend SikkerKeyError. Typed errors cover configuration, authentication, access, missing resources, conflicts, rate limits, temporary service availability, invalid structured data, and missing fields. Network failures and timeouts use ApiError with httpStatus === 0.

Retries and timeout

Authenticated requests retry network failures and HTTP 429 or 503 responses up to three times, waiting 1, 2, and 4 seconds. Every attempt uses a fresh timestamp and nonce. Connection and total request timeouts are 15 seconds.


#Method reference

Task

Method

Connect with a registered identity

SikkerKey::create(vaultOrPath?)

Create an ephemeral identity

SikkerKey::bootstrapInMemory(...)

Read a standard secret

getSecret(secretId)

Read structured fields

getFields(secretId) / getField(secretId, field)

List secrets

listSecrets() / listSecretsByProject(projectId)

Export configuration

export(projectId?)

Enable encrypted fallback

enableCache(maxAge?, onFallback?)

List local vaults

SikkerKey::listVaults()


#Source code and license

The PHP SDK is open source under the MIT License. Review the source, report an issue, or contribute through the SikkerKeyOfficial GitHub organization.