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.
Middlewares
Automatic integration via middleware — every HTTP request is captured without modifying any controller. Click the framework to see the complete code.
Terminable middleware with handle() + terminate(). terminate() runs after the response is sent — naturally fire-and-forget.
public function terminate($request, $response): void
{
$this->emit($request, $response);
// roda DEPOIS da resposta enviada
}View full documentation →
EventSubscriber on kernel.response/kernel.exception + kernel.terminate to send after the response, using Symfony HttpClient.
public static function getSubscribedEvents(): array
{
return [
KernelEvents::TERMINATE => 'onTerminate',
KernelEvents::EXCEPTION => 'onException',
];
}View full documentation →
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
// 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).
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
// 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 meta | What it does in the SIEM |
|---|---|
event_name | The 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_ip | Becomes source.ip with maximum precedence and provenance client_asserted. See the section below. |
immutable_trail | Becomes imtbl.immutable_trail — groups related events for investigation (e.g. one order, one user). |
type | Event severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.) |
service, env, request_id | Metadata: 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 — it does not drop the event.
- Writes to
source.ipwith 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.
client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IPProvenance and trust
client_ip is asserted by the tenant — the client's backend claims the IP, and it is spoofable by whoever controls that backend. However it is self-contained to 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
Take the first IP from X-Forwarded-For (closest to the user); as a fallback, use the connection IP.
function client_ip(): ?string {
$xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
if ($xff !== '') {
return trim(explode(',', $xff)[0]); // primeiro hop = IP do usuario
}
return $_SERVER['REMOTE_ADDR'] ?? null;
}
$meta = ['event_name' => 'user.login', 'client_ip' => client_ip()];Payload example
{
"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.
