# Proxy with plain PHP

> Serve the Reveata script and forward events through two small PHP files, with the visitor's IP and your proxy secret.

Two PHP files on your own domain stand in for Reveata's addresses: one returns the script, one forwards events. They need PHP with the curl extension, which most hosts include. For Laravel or WordPress, use the routes in [Proxy through your own server](https://reveata.com/docs/self-hosted-proxy) instead.

## Before you start

1. In Reveata, open your website, then **Settings → General → Tracking code**, and choose **Create proxy secret** under **Proxy secret** (admins and the owner can). Copy it: it starts with `dt_proxy_` and is shown once.
2. Make it available to PHP as the environment variable `REVEATA_PROXY_SECRET`, never in a file the browser can download:
   - Apache with `mod_php`: `SetEnv REVEATA_PROXY_SECRET dt_proxy_…` in the `VirtualHost` configuration.
   - PHP-FPM: `env[REVEATA_PROXY_SECRET] = dt_proxy_…` in the pool file, then reload PHP-FPM.
   - A host with an environment variables panel: add it there.

## The script: `dt/script.php`

```php
<?php
// dt/script.php: returns the Reveata script from your domain.
$ch = curl_init('https://reveata.com/js/script.js');
$headers = [];
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) {
        $parts = explode(':', $line, 2);
        if (count($parts) === 2) {
            $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
        }
        return strlen($line);
    },
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE) ?: 502;
curl_close($ch);

http_response_code($status);
header('Content-Type: text/javascript; charset=utf-8');
header('Cache-Control: ' . ($headers['cache-control'] ?? 'public, max-age=86400'));
if (isset($headers['etag'])) {
    header('ETag: ' . $headers['etag']);
}
echo $body === false ? '' : $body;
```

## Events: `dt/event.php`

```php
<?php
// dt/event.php: forwards events with the visitor's IP and your proxy secret.
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}
$body = file_get_contents('php://input', false, null, 0, 16385);
if ($body === false || strlen($body) > 16384) {
    http_response_code(413);
    exit;
}

$headers = [
    'Content-Type: text/plain',
    'X-Reveata-Proxy-Secret: ' . (getenv('REVEATA_PROXY_SECRET') ?: ''),
    'X-Reveata-Client-IP: ' . ($_SERVER['REMOTE_ADDR'] ?? ''),
];
$pass = [
    'User-Agent' => 'HTTP_USER_AGENT',
    'Accept-Language' => 'HTTP_ACCEPT_LANGUAGE',
    'Origin' => 'HTTP_ORIGIN',
    'Referer' => 'HTTP_REFERER',
    'Sec-Fetch-Dest' => 'HTTP_SEC_FETCH_DEST',
    'Sec-Fetch-Mode' => 'HTTP_SEC_FETCH_MODE',
    'Sec-Fetch-Site' => 'HTTP_SEC_FETCH_SITE',
];
foreach ($pass as $name => $key) {
    if (!empty($_SERVER[$key])) {
        $headers[] = $name . ': ' . $_SERVER[$key];
    }
}

$diagnostic = null;
$ch = curl_init('https://reveata.com/api/collect');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$diagnostic) {
        if (stripos($line, 'x-reveata-proxy:') === 0) {
            $diagnostic = trim(substr($line, 17));
        }
        return strlen($line);
    },
]);
curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE) ?: 502;
curl_close($ch);

header('Cache-Control: no-store');
if ($diagnostic !== null) {
    header('x-reveata-proxy: ' . $diagnostic); // why the forwarded IP was or wasn't used
}
http_response_code($status);
```

The event file sends the visitor's browser headers and leaves out your cookies: Reveata reads its ids from the body, so it needs none of them.

## Point the snippet at them

```html
<script defer data-website-id="ws_your_tracking_id" data-api="/dt/event.php" src="/dt/script.php"></script>
```

The paths can be anything you like. To hide the `.php`, rewrite `/dt/script.js` and `/dt/event` to these files on your web server, and use those paths in the snippet.

## Behind a load balancer or CDN

`REMOTE_ADDR` is the address that connected to PHP. Behind Cloudflare, a load balancer or a reverse proxy, that is their address, not the visitor's. Set your web server to restore the visitor's address first (Apache `mod_remoteip`, Nginx `real_ip_header`), or read the header your provider sets, such as `CF-Connecting-IP` on Cloudflare. Only trust such a header when requests can reach PHP through that provider alone.

## Check it works

Open `/dt/script.php` in your browser: you should see the script. Then visit your site and open **Realtime** in Reveata: your visit should appear within seconds, located in your own city. If it shows your server's location instead, open the network tab of your browser's developer tools, select the request to `/dt/event.php` and read its `x-reveata-proxy` response header (`event.php` passes it on):

| `x-reveata-proxy`        | Meaning                                                                    |
| ------------------------- | -------------------------------------------------------------------------- |
| `trusted`                 | Secret accepted; the visitor's address is used.                            |
| `proxy_secret_invalid`    | The secret is missing, mistyped, rotated or deleted.                       |
| `proxy_client_ip_invalid` | The secret is right, but `X-Reveata-Client-IP` is empty or not an IP.     |

More checks are in [Proxy through your own server](https://reveata.com/docs/self-hosted-proxy#check-that-it-works).
