Skip to main content
ImmutableLog logo

PHP

Complete integration guide for ImmutableLog in PHP. Automatic middleware for Laravel and Symfony, or a direct Guzzle HTTP client for workers, commands, and queue jobs. Use terminable middleware (Laravel) or kernel.terminate (Symfony) to send after the response.

Direct HTTP client (Guzzle)

Use the ImmutableLog class to send events directly without depending on a web framework. Ideal for artisan/console commands, queue workers, and any PHP script that needs to record events.

php
<?php
// src/ImmutableLog.php
// composer require guzzlehttp/guzzle ramsey/uuid

use GuzzleHttp\Client;
use Ramsey\Uuid\Uuid;

final class ImmutableLog
{
    private Client $http;

    public function __construct(
        private string $apiKey,
        private string $service = 'php-service',
        private string $env = 'production',
        ?string $apiUrl = null,
    ) {
        $this->http = new Client([
            'base_uri' => $apiUrl ?? (getenv('IMTBL_URL') ?: 'https://api.immutablelog.com'),
            'timeout'  => 5,
        ]);
    }

    public function sendEvent(
        string $eventName,
        string $kind,                 // "success" | "info" | "error"
        array $payload,
        ?string $immutableTrail = null,
    ): void {
        $requestId = Uuid::uuid4()->toString();
        $trail = self::sanitizeTrail($immutableTrail);

        // Todos os valores de meta precisam ser strings.
        $meta = [
            'type'       => $kind,
            'event_name' => $eventName,
            'service'    => $this->service,
            'request_id' => $requestId,
            'env'        => $this->env,
        ];
        if ($trail !== null) {
            $meta['immutable_trail'] = $trail;
        }

        $event = [
            'payload' => json_encode($payload + ['timestamp' => gmdate('c')]),
            'meta'    => $meta,
        ];

        $headers = [
            'Authorization' => "Bearer {$this->apiKey}",
            'Content-Type'  => 'application/json',
            // Idempotency-Key e OBRIGATORIO (sem ele a API responde 400).
            'Idempotency-Key'         => "{$eventName}-{$requestId}",
            'Request-Id'              => $requestId,
            'X-Client-TZ'             => 'America/Sao_Paulo',
            'X-Client-Offset-Minutes' => '-180',
        ];
        if ($trail !== null) {
            $headers['X-Imtbl-Trail'] = $trail;
        }

        $this->http->post('/v1/events', [
            'headers' => $headers,
            'json'    => $event,
        ]);
    }

    // Normaliza o immutable_trail (trim, nao-vazio, max 256, sem ':').
    // O servidor responde 400 invalid_immutable_trail se a regra for violada.
    public static function sanitizeTrail(?string $value): ?string
    {
        if ($value === null) {
            return null;
        }
        $v = trim($value);
        if ($v === '') {
            return null;
        }
        $v = str_replace(':', '-', $v);
        if (mb_strlen($v) > 256) {
            $v = mb_substr($v, 0, 256);
        }
        return $v;
    }
}

// Uso / Usage
$log = new ImmutableLog(getenv('IMTBL_API_KEY'), 'payments-service', 'production');
$log->sendEvent('payment.approved', 'success', [
    'payment_id' => 'pay_abc123',
    'amount'     => 299.90,
], immutableTrail: 'order-7782');

PHP is synchronous per request. To avoid blocking the user, send events from a queue job (Laravel Queue / Symfony Messenger) or from a terminable middleware.

Retry with exponential backoff

For high-availability production, add retry with exponential backoff. ImmutableLog returns 202 on success and 200 on an idempotent duplicate. Never retry on 429 (monthly limit reached).

php
public function sendWithRetry(
    string $eventName,
    string $kind,
    array $payload,
    ?string $trail = null,
    int $maxAttempts = 3,
): void {
    $delayMs = 500;

    for ($attempt = 0; $attempt < $maxAttempts; $attempt++) {
        try {
            $this->sendEvent($eventName, $kind, $payload, $trail);
            return;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            $status = $e->getResponse()?->getStatusCode();

            // 429 = limite mensal - nao fazer retry.
            if ($status === 429) {
                return;
            }
            if ($attempt + 1 < $maxAttempts) {
                usleep($delayMs * 1000);
                $delayMs *= 2; // 500ms -> 1s -> 2s
            }
        }
    }
}

Sensitive data hashing

Never send raw personal data (email, CPF, IP) to ImmutableLog. Use SHA-256 to generate a deterministic digest, traceable without exposing the original data.

php
<?php
// Faz o hash de dados sensiveis antes de enviar - nunca logue PII bruto.
function sha256_hex(string $data): string
{
    return hash('sha256', $data);
}

// Uso no payload do evento:
$payload = [
    'user_id'    => 'usr_123',
    'email_hash' => sha256_hex('user@example.com'),
    'ip_hash'    => sha256_hex('192.168.1.1'),
];

meta fields

Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.

Field in metaWhat it does in the SIEM
event_nameThe event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below.
immutable_trailBecomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user).
typeEvent severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageSent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error.
service, env, request_idMetadata: indexed and queryable in the dashboard (search/filters).

client_ip: end-user IP

The problem it solves

Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)

The solution

The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.

How the SIEM handles it

  • Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g. 1.2.3.4:5678) is also silently discarded.
  • Writes to source.ip with maximum precedence (see order below).
  • Stamps imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge.
  • Feeds GeoIP, threat intel and IP-based detection rules.
source.ip precedence:client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IP

Provenance and trust

client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.

How to obtain the IP in your backend

Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).

Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.

php
function bare_ip(?string $value): ?string {
    $v = trim((string) $value);
    if ($v === '') return null;
    if ($v[0] === '[') {
        $end = strpos($v, ']');
        if ($end === false) return null;
        $rest = substr($v, $end + 1);
        if ($rest !== '' && !preg_match('/^:\d+$/', $rest)) return null;
        $v = substr($v, 1, $end - 1);
    } elseif (substr_count($v, ':') === 1) {
        $v = explode(':', $v, 2)[0]; // 1.2.3.4:5678 -> 1.2.3.4
    }
    if (strpos($v, '%') !== false) return null; // zona IPv6 (fe80::1%eth0) nao e IP puro
    return filter_var($v, FILTER_VALIDATE_IP) !== false ? $v : null;
}

// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
function client_ip(): ?string {
    $xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    if ($xff !== '' && ($ip = bare_ip(explode(',', $xff)[0])) !== null) return $ip;
    if (($ip = bare_ip($_SERVER['HTTP_X_REAL_IP'] ?? null)) !== null) return $ip;
    return bare_ip($_SERVER['REMOTE_ADDR'] ?? null);
}

$meta = ['event_name' => 'user.login'];
$ip = client_ip();
if ($ip !== null) {
    $meta['client_ip'] = $ip; // sem IP valido, omita a chave (nunca "unknown")
}

Payload example

json
{
  "payload": "{\"user\":\"bob\",\"action\":\"login\"}",
  "meta": {
    "event_name": "user.login",
    "client_ip": "179.110.4.205",
    "immutable_trail": "user-bob"
  }
}

PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.

This documentation reflects the current API behavior. For questions or advanced integrations, contact the support team.

Back to docs