Pular para o conteúdo principal
ImmutableLog logo
← Voltar
SymfonyPHP

Integração com Symfony

Integre o ImmutableLog em qualquer aplicação Symfony com um EventSubscriber de três listeners: `kernel.request` marca o início, `kernel.exception` guarda a exceção, e `kernel.terminate` (que o Symfony dispara depois de entregar a resposta ao cliente) monta e envia o evento via cURL. Uma falha de envio só gera um `warning` no logger. Leia a seção sobre PHP-FPM antes de usar em produção.

Instalação

Não há pacote Composer: você copia o arquivo `ImmutableLogSubscriber.php` do GitHub para `src/EventSubscriber/ImmutableLogSubscriber.php`. Ele usa só `ext-curl` e `ext-json` (presentes nas imagens oficiais do PHP) e componentes que o `symfony/framework-bundle` já traz (`http-kernel`, `routing`, `psr/log`). Symfony 6.4 ou mais novo (testado no 8.1), PHP 8.1+. O arquivo declara `namespace App\EventSubscriber;`.

bash
src/EventSubscriber/ImmutableLogSubscriber.php   # conteúdo do ImmutableLogSubscriber.php

Código do EventSubscriber

Este é o arquivo inteiro. `onRequest` marca o início da requisição principal (exceto `OPTIONS` e os paths em `SKIP_PATHS`); `onException` guarda a exceção; `onTerminate` monta o evento e o envia depois da resposta. Exceção não tratada também gera evento, com status 500 e `error_*`. Os paths ignorados, o uso do header de trilha e o timeout são constantes no topo da classe (`SKIP_PATHS`, `TRUST_TRAIL_HEADER`, `TIMEOUT_MS`): edite no seu arquivo.

php
<?php

// ImmutableLog event subscriber for Symfony (6.4, 7.x).
//
// Copy this file to src/EventSubscriber/ImmutableLogSubscriber.php. With the default
// services.yaml (autowire + autoconfigure) nothing else is needed: the kernel.event_subscriber
// tag is applied automatically. Uses only ext-curl and ext-json; no Composer package.

namespace App\EventSubscriber;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;

final class ImmutableLogSubscriber implements EventSubscriberInterface
{
    private const DEFAULT_API_URL = 'https://api.immutablelog.com';
    private const SKIP_PATHS = ['/health', '/healthz'];
    private const CONNECT_TIMEOUT_MS = 1000;
    private const TIMEOUT_MS = 5000;
    private const MAX_ERROR_MESSAGE = 500;
    private const MAX_PATH = 2048;
    private const MAX_USER_AGENT = 512;
    private const MAX_TRAIL = 256;

    /** Read X-Imtbl-Trail from the request when the controller sets no trail. Off: caller-controlled. */
    private const TRUST_TRAIL_HEADER = false;

    /** @var array<string, string> route name -> path template, kept for the process lifetime */
    private static array $routePaths = [];

    private LoggerInterface $logger;

    public function __construct(?LoggerInterface $logger = null, private ?RouterInterface $router = null)
    {
        $this->logger = $logger ?? new NullLogger();
    }

    public static function getSubscribedEvents(): array
    {
        return [
            // High priority: start the clock before the router and the firewall.
            KernelEvents::REQUEST => ['onRequest', 4096],
            KernelEvents::EXCEPTION => ['onException', 4096],
            KernelEvents::TERMINATE => 'onTerminate',
        ];
    }

    public function onRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }
        $req = $event->getRequest();
        if ($req->getMethod() === 'OPTIONS' || in_array($req->getPathInfo(), self::SKIP_PATHS, true)) {
            return;
        }
        $req->attributes->set('imtbl.started_at', microtime(true));
    }

    public function onException(ExceptionEvent $event): void
    {
        if ($event->isMainRequest()) {
            $event->getRequest()->attributes->set('imtbl.exception', $event->getThrowable());
        }
    }

    /**
     * kernel.terminate runs after the response was sent (under PHP-FPM, after
     * fastcgi_finish_request()), so the POST to ImmutableLog never delays it.
     */
    public function onTerminate(TerminateEvent $event): void
    {
        $req = $event->getRequest();
        if (!$req->attributes->has('imtbl.started_at')) {
            return; // skipped (OPTIONS, health)
        }
        try {
            $apiKey = self::env('IMTBL_API_KEY', '');
            if ($apiKey === '') {
                return;
            }
            [$requestId, $body] = $this->buildEvent($req, $event->getResponse());
            $this->send(rtrim(self::env('IMTBL_URL', self::DEFAULT_API_URL), '/').'/v1/events', $apiKey, $requestId, $body);
        } catch (\Throwable $e) {
            $this->logger->warning('[ImmutableLog] failed to send event: '.$e->getMessage());
        }
    }

    /** Symfony's Dotenv fills $_SERVER/$_ENV, not getenv(): look in all three. */
    private static function env(string $name, string $default): string
    {
        $v = $_SERVER[$name] ?? $_ENV[$name] ?? getenv($name);

        return ($v === false || $v === null || $v === '') ? $default : (string) $v;
    }

    /** @return array{0: string, 1: string} */
    private function buildEvent(Request $req, Response $res): array
    {
        $status = $res->getStatusCode();
        $kind = $status >= 400 ? 'error' : ($status >= 300 ? 'info' : ($status >= 200 ? 'success' : 'info'));
        $method = $req->getMethod();
        $path = mb_substr($req->getPathInfo(), 0, self::MAX_PATH);
        $requestId = self::uuid4();
        $latencyMs = (int) round((microtime(true) - (float) $req->attributes->get('imtbl.started_at')) * 1000);
        $clientIp = self::clientIp($req->headers->get('X-Forwarded-For'), $req->headers->get('X-Real-IP'), $req->server->get('REMOTE_ADDR'));
        $service = self::env('IMTBL_SERVICE_NAME', 'symfony-service');
        $env = self::env('IMTBL_ENV', 'production');

        $eventName = $req->attributes->get('imtbl.event_name') ?: "http.$method.$path";
        $trailSource = $req->attributes->get('imtbl.trail');
        if ($trailSource === null && self::TRUST_TRAIL_HEADER) {
            $trailSource = $req->headers->get('X-Imtbl-Trail');
        }
        $trail = self::sanitizeTrail($trailSource);

        $exception = $req->attributes->get('imtbl.exception');
        $errorType = $exception instanceof \Throwable ? get_class($exception) : null;
        $errorMessage = $exception instanceof \Throwable ? $exception->getMessage() : null;

        $payload = [
            'id' => self::uuid4(),
            'kind' => $kind,
            'message' => "$method $path -> $status",
            'timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'context' => [
                'ip' => $clientIp ?? 'unknown',
                'user_agent' => mb_substr((string) $req->headers->get('User-Agent'), 0, self::MAX_USER_AGENT),
            ],
            'request' => ['request_id' => $requestId, 'method' => $method, 'path' => $path],
            'metrics' => ['latency_ms' => $latencyMs, 'status_code' => $status],
            'severity' => $kind === 'error' ? 'high' : 'low',
        ];
        if ($kind === 'error') {
            $payload['error'] = [
                'status_code' => $status,
                'retryable' => in_array($status, [408, 429, 500, 502, 503, 504], true),
            ];
            if ($errorType !== null) {
                $payload['error']['exception'] = $errorType;
                $payload['error']['exception_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }

        // meta is a string -> string map in the core: every value is cast with (string).
        // http_status goes as "200", never as the integer 200.
        $meta = [
            'type' => $kind,
            'event_type' => $kind,
            'event_name' => (string) $eventName,
            'service' => $service,
            'request_id' => $requestId,
            // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
            'env' => $env,
            'environment' => $env,
            'http_method' => $method,
            'http_status' => (string) $status,
            'http_route' => $this->routeTemplate($req) ?? $path,
            'log_level' => match ($kind) { 'error' => 'error', 'warning' => 'warn', 'debug' => 'debug', default => 'info' },
        ];
        if ($clientIp !== null) {
            $meta['client_ip'] = $clientIp;
        }
        if ($errorType !== null) {
            $meta['error_type'] = $errorType;
            if ((string) $errorMessage !== '') {
                $meta['error_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }
        if ($trail !== null) {
            $meta['immutable_trail'] = $trail;
        }

        $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR;

        return [$requestId, json_encode(['payload' => json_encode($payload, $flags), 'meta' => $meta], $flags)];
    }

    /**
     * Route template ("/users/{id}"). The request only carries the route NAME (_route); the
     * path comes from the route collection. Null on a 404 (no _route): the caller uses the path.
     */
    private function routeTemplate(Request $req): ?string
    {
        $name = $req->attributes->get('_route');
        if (!is_string($name) || $name === '' || $this->router === null) {
            return null;
        }
        if (!array_key_exists($name, self::$routePaths)) {
            self::$routePaths[$name] = $this->router->getRouteCollection()->get($name)?->getPath() ?? '';
        }

        return self::$routePaths[$name] !== '' ? self::$routePaths[$name] : null;
    }

    private function send(string $url, string $apiKey, string $idempotencyKey, string $body): void
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer '.$apiKey,
                'Idempotency-Key: '.$idempotencyKey,
            ],
            CURLOPT_RETURNTRANSFER => true,
            // Runs after the client got the response, but holds the PHP-FPM worker until done.
            CURLOPT_CONNECTTIMEOUT_MS => self::CONNECT_TIMEOUT_MS,
            CURLOPT_TIMEOUT_MS => self::TIMEOUT_MS,
        ]);
        $result = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($result === false) {
            $this->logger->warning('[ImmutableLog] failed to send event: '.curl_error($ch));
        } elseif ($status >= 400) {
            $this->logger->warning("[ImmutableLog] event rejected: HTTP $status");
        }
        curl_close($ch);
    }

    /**
     * client_ip for the SIEM: first entry of X-Forwarded-For, then X-Real-IP, then REMOTE_ADDR.
     * Only a bare IP is returned (no port): the SIEM drops "ip:port" silently. The headers are
     * read directly, without framework.trusted_proxies; see "Proxy e X-Forwarded-For" in the README.
     */
    public static function clientIp(?string $xff, ?string $realIp, ?string $remoteAddr): ?string
    {
        $first = $xff !== null ? explode(',', $xff)[0] : null;

        return self::bareIp($first) ?? self::bareIp($realIp) ?? self::bareIp($remoteAddr);
    }

    /** "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP. */
    private static function bareIp(?string $raw): ?string
    {
        $s = trim((string) $raw);
        if ($s === '') {
            return null;
        }
        if ($s[0] === '[') {
            $end = strpos($s, ']');
            $s = $end === false ? '' : substr($s, 1, $end - 1);
        } elseif (substr_count($s, ':') === 1) {
            $s = explode(':', $s)[0];
        }
        if (filter_var($s, FILTER_VALIDATE_IP) === false) {
            return null;
        }
        // "::ffff:10.0.0.1" -> "10.0.0.1"
        if (stripos($s, '::ffff:') === 0 && filter_var(substr($s, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
            return substr($s, 7);
        }

        return $s;
    }

    /** The core rejects a trail that is empty, longer than 256 chars or contains ':'. */
    private static function sanitizeTrail(mixed $value): ?string
    {
        if (!is_scalar($value)) {
            return null;
        }
        $s = mb_substr(str_replace(':', '-', trim((string) $value)), 0, self::MAX_TRAIL);

        return $s === '' ? null : $s;
    }

    private static function uuid4(): string
    {
        $b = random_bytes(16);
        $b[6] = chr((ord($b[6]) & 0x0F) | 0x40);
        $b[8] = chr((ord($b[8]) & 0x3F) | 0x80);

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
    }
}

Registro e configuração

Com o `config/services.yaml` padrão (`autowire: true`, `autoconfigure: true` e `App\` carregado de `src/`), não há nada a registrar: o subscriber é detectado e recebe a tag `kernel.event_subscriber`. O `LoggerInterface` e o `RouterInterface` do construtor são injetados por autowiring (os dois são opcionais). Sem autoconfigure, registre à mão.

yaml
# Verifique o registro:
bin/console debug:event-dispatcher kernel.terminate
#  App\EventSubscriber\ImmutableLogSubscriber::onTerminate()

# Sem autoconfigure, registre à mão em config/services.yaml:
services:
    App\EventSubscriber\ImmutableLogSubscriber:
        tags: [kernel.event_subscriber]

O subscriber lê `$_SERVER`, `$_ENV` e `getenv()`, nessa ordem. O Dotenv do Symfony preenche os dois primeiros, então `.env`, `.env.local` e `secrets:set` funcionam. Sem chave, o subscriber não envia nada.

bash
# .env.local (fora do git)
IMTBL_API_KEY=iml_live_xxxxxxxxxxxxxxxx
IMTBL_SERVICE_NAME=meu-servico-symfony
IMTBL_ENV=production
VariávelObrigatóriaDescrição
IMTBL_API_KEYSimChave de API do ImmutableLog, com scope `events:write`
IMTBL_URLNãoURL base da API (padrão `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENãoNome do serviço (`meta.service`); padrão `symfony-service`
IMTBL_ENVNãoAmbiente (`meta.environment` e `meta.env`); padrão `production`

Nunca coloque a chave no código nem no repositório: use o .env.local fora do git, `bin/console secrets:set IMTBL_API_KEY` ou um secrets manager. No PHP-FPM, com `clear_env = yes` (o padrão), variáveis exportadas só no ambiente do processo não chegam ao PHP; use o .env.local, os secrets do Symfony ou `env[IMTBL_API_KEY] = ...` no pool do FPM.

Como funciona

kernel.request

Prioridade 4096. Marca imtbl.started_at na request principal (exceto OPTIONS e paths ignorados)

kernel.exception

Prioridade 4096. Guarda a exceção em imtbl.exception

kernel.terminate

Roda após a resposta: lê status, rota, exceção e marcadores; monta o evento; POST via cURL

Idempotency-Key

Um UUID v4 novo por evento, igual a meta.request_id. O X-Request-Id recebido não é usado, porque vem do chamador e dois eventos diferentes com o mesmo valor seriam descartados como duplicata

body

O subscriber nunca lê o body da requisição: nem conteúdo, nem hash. Sub-requests não geram evento próprio

Envio, PHP-FPM e o tempo de resposta

PHP não tem thread em segundo plano: o POST roda no mesmo processo, no `kernel.terminate`. O modo de servir a aplicação muda o efeito.

Como é servidaEfeito do envio
PHP-FPMO cliente recebe a resposta sem esperar o envio (o `fastcgi_finish_request()` roda antes). Mas o worker do FPM fica ocupado até o envio terminar, no máximo o timeout. Com o ImmutableLog lento, os workers ficam presos e as requisições seguintes esperam na fila do pool (o padrão são 5 workers).
symfony server:start / php -SNão há `fastcgi_finish_request()`: a conexão só fecha depois do kernel.terminate. Com o ImmutableLog lento, cada resposta atrasa até o timeout (medido: 5 s com o core travado). Use só em desenvolvimento.

Mantenha `TIMEOUT_MS` baixo (o padrão do arquivo é 5000) e dimensione o pool do FPM. Para isolar de vez, mova o envio para o Messenger, o que não está neste arquivo. Com o ImmutableLog fora do ar (conexão recusada), não há efeito visível.

Evento e trilha customizados

Defina os atributos `imtbl.event_name` e `imtbl.trail` na request dentro de qualquer controller. O `onTerminate` lê esses valores ao montar o evento.

php
#[Route('/payments', name: 'payments', methods: ['POST'])]
public function create(Request $request): JsonResponse
{
    $request->attributes->set('imtbl.event_name', 'payment.created');
    $request->attributes->set('imtbl.trail', 'order-7782');

    return new JsonResponse(['ok' => true], 201);
}

Padrão automático: http.METHOD.path.

Trilha imutável (immutable_trail)

A trilha agrupa eventos relacionados em uma mesma linha do tempo auditável e vai em `meta.immutable_trail`. Defina o atributo `imtbl.trail` na request. O valor passa por `sanitizeTrail` antes do envio.

php
#[Route('/flows/{id}/run', methods: ['POST'])]
public function run(Request $request, string $id): JsonResponse
{
    $request->attributes->set('imtbl.trail', "flow-{$id}");
    // ... business logic ...
    return new JsonResponse(['status' => 'ok']);
}

A trilha não pode ser vazia, exceder 256 caracteres ou conter `:`, e violações retornam `400 invalid_immutable_trail`. Por isso o `sanitizeTrail` troca `:` por `-`, corta em 256 e omite a chave se sobrar vazio.

O header `X-Imtbl-Trail` é opcional e fica desligado por padrão. Só é lido com `TRUST_TRAIL_HEADER = true` (constante no topo da classe), e só quando o controller não definiu a trilha. O header vem de quem chama o serviço, então qualquer chamador poderia pendurar eventos numa trilha alheia do mesmo tenant. Ligue só quando o serviço recebe chamadas apenas de serviços internos seus.

Resposta e códigos de status

A API de ingestão é assíncrona. Sucesso retorna 202 (novo) ou 200 (duplicata idempotente). O envio acontece em `kernel.terminate` e uma recusa só gera um `warning` no logger, então esses códigos importam principalmente se você enviar eventos manualmente.

StatusSignificado
202Evento aceito e enfileirado (novo)
200Idempotency-Key já existente (duplicate: true)
400Idempotency-Key ausente/vazia ou invalid_immutable_trail
403Assinatura inativa/expirada, escopo ou retenção
413payload_too_large (limite do servidor: 16KB)
429monthly_limit_exceeded, não fazer retry
503mempool_full, transitório, pode dar retry

Campos de meta

Além do payload, o objeto meta carrega os campos que o SIEM usa para normalizar (ECS) e enriquecer o evento. Todos os valores de meta são strings.

Campo em metaO que faz no SIEM
event_nameO rótulo do evento (ex.: http.GET.auth-me-user, Pagamento erro), o identificador que aparece na listagem. Vira event.action e deriva event.category (ex.: nome com login → authentication).
client_ipVira source.ip com precedência máxima e proveniência client_asserted. É o único campo de meta que vira source.ip. Deve ser IP puro, sem porta. Ver a seção abaixo.
immutable_trailVira imtbl.immutable_trail, que agrupa eventos relacionados para investigação (ex.: um pedido, um usuário).
typeSeveridade do evento: error / warning / info / success. Colore o badge na listagem. (event_type é aceito como sinônimo.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageEnviados pelos middlewares, sempre como string (inclusive http_status, ex.: "200"). error_type e error_message só existem quando há erro.
service, env, request_idMetadados: indexados e consultáveis no painel (busca/filtros).

client_ip: IP do usuário final

O problema que resolve

Entre o navegador e o core há proxies/ALB. O IP que o core observa na conexão é o do salto anterior (o backend do cliente ou um proxy da AWS), não o do usuário. Sem ação, source.ip seria o IP do proxy, inútil para geo, threat e detecção por IP. (Exemplo real: o XFF chegava 44.192.13.3 (AWS) enquanto o usuário era 179.110.4.205.)

A solução

O backend do cliente é o único que enxerga o IP real do navegador, então ele encaminha esse IP em meta.client_ip ao chamar POST /v1/events.

Como o SIEM trata

  • Valida que é um IP (v4/v6). Um valor que não seja IP é ignorado, sem derrubar o evento. Um IP com porta (ex.: 1.2.3.4:5678) também é descartado em silêncio.
  • Escreve em source.ip com precedência máxima (ver ordem abaixo).
  • Carimba imtbl.source_ip_origin = "client_asserted"; a UI mostra o selo “IP do usuário”.
  • Alimenta GeoIP, threat intel e regras de detecção por IP.
Precedência de source.ip:client_ipX-Forwarded-For (1º hop)X-Real-IPIP de conexão

Proveniência e confiança

client_ip é asserido pelo tenant: o backend do cliente afirma o IP, e o valor é falsificável por quem controla aquele backend. Porém ele fica contido no próprio tenant (não cruza a fronteira de outro tenant). Um hit de threat/geo sobre um client_asserted é uma alegação, não uma observação de borda.

Como obter o IP no seu backend

Teste os candidatos na ordem: o primeiro IP do X-Forwarded-For (o mais próximo do usuário), depois o X-Real-IP (se o seu proxy o define) e por fim o IP de conexão. Cada candidato passa por uma função que remove a porta (1.2.3.4:5678, [2001:db8::1]:8080) e os colchetes e valida que é um IP de verdade, sem consultar DNS. Um valor inválido (lixo, localhost, zona IPv6 como fe80::1%eth0) é ignorado e o próximo candidato é tentado. Envie IP puro, sem porta, e se nenhum candidato for um IP válido omita a chave client_ip (meta não aceita null, e nunca envie “unknown”).

Só atrás de proxy confiável: ler o primeiro IP do X-Forwarded-For só é seguro quando há um proxy ou ALB confiável na frente da aplicação, que sobrescreve ou acrescenta o header. Sem proxy, o cliente controla o header e pode forjar o IP, e o SIEM promoverá esse valor a 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")
}

Exemplo de payload

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

Nota de PII: client_ip é PII e vai selado no bloco imutável (permanente). Decida conscientemente entre evidência forense e “direito ao esquecimento” antes de enviá-lo.

Esta documentação reflete o comportamento atual da integração. Para dúvidas ou integrações avançadas, entre em contato com o time de suporte.

Voltar para PHP