> Markdown version of https://tuna.am/en/docs/guides/install/sdk/php/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# PHP

The PHP SDK opens Tuna tunnels from your code: expose a local HTTP or TCP service at a public address. Use it to receive webhooks during development, show a local site, or give CI access to a local database.

The package runs [tuna-tiny](https://tuna.am/en/docs/guides/install/install-tiny.md) as a child process and reports its events. It needs the `proc_open` function, so the SDK does not work on shared hosting where that function is disabled.

The package is [yuccastream/tuna-sdk-php](https://packagist.org/packages/yuccastream/tuna-sdk-php) on Packagist, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-php).

## Installation

```shell
composer require yuccastream/tuna-sdk-php

```

Requires PHP 8.1 or later, no PHP dependencies. For CLI scripts we recommend `ext-pcntl`: with it, SIGTERM and Ctrl+C close the tunnel cleanly.

The SDK looks for the tuna-tiny binary in this order:

1. the `binary` option;
2. `tuna-tiny` in `PATH`;
3. downloads the tuna-tiny version pinned to the package version from `releases.tuna.am`, verifies its SHA-256 against the checksums shipped in the package, and caches it in `$XDG_CACHE_HOME/tuna-sdk-php` (or `~/.cache/tuna-sdk-php`, `%LOCALAPPDATA%\tuna-sdk-php`). Set `cacheDir` to use a different directory.

Prebuilt tuna-tiny binaries are available for Linux, macOS, Windows, FreeBSD and OpenBSD on amd64 and arm64.

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) with **Run tunnels** enabled (the **For tunnels** preset) and pass it in the `TUNA_API_KEY` environment variable or the `apiKey` option. tuna-tiny receives the key through the environment, not on the command line.

## Forward to a local service

```php
<?php
require __DIR__ . '/vendor/autoload.php';

use Tuna\Event;
use Tuna\Tunnel;

$tunnel = Tunnel::forward([
    'protocol' => 'http',
    'onEvent' => function (Event $e): void {
        if ($e->type === Event::RECONNECTING) {
            fwrite(STDERR, "connection lost: {$e->error}, retry in {$e->retryIn}s\n");
        }
    },
], '8080');

echo "Forwarding {$tunnel->url()} -> localhost:8080\n";

pcntl_async_signals(true);
pcntl_signal(SIGINT, fn () => $tunnel->close());
$tunnel->wait();

```

`forward()` returns once the tunnel is up. `wait()` blocks until the tunnel stops: it returns after `close()` and throws on a permanent error. Instead of `wait()`, you can iterate over events:

```php
foreach ($tunnel->events() as $event) {
    echo $event->type, ' ', $event->url ?? $event->error ?? '', "\n";
}

```

A TCP tunnel to a local PostgreSQL, open to a single network only:

```php
$tunnel = Tunnel::forward([
    'protocol' => 'tcp',
    'cidrAllow' => ['203.0.113.0/24'],
], '127.0.0.1:5432');
echo $tunnel->url(), "\n";

```

The local address is a port (`8080`), `host:port`, `http://host:port` or `unix:///path/to.sock`.

## Options

| Option                  | Meaning                                                                                                                                                          |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`              | `http` (default) or `tcp`                                                                                                                                        |
| `apiKey`                | API key, defaults to `TUNA_API_KEY`                                                                                                                              |
| `subdomain`, `domain`   | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `port`                  | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `proxyProtocol`         | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `cidrAllow`, `cidrDeny` | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `serverURL`             | API address, defaults to `https://api.tuna.am`                                                                                                                   |
| `connectTimeout`        | limit on the wait for the first connection, in seconds; `0` means no limit                                                                                       |
| `onEvent`               | callback that receives every `Tuna\Event`                                                                                                                        |
| `binary`, `cacheDir`    | path to tuna-tiny and the download cache, see [Installation](#installation)                                                                                      |

## Events and errors

`Tuna\Event` has a `type` and, depending on the type, `url`, `message`, `reason`, `error`, `retryIn` and `expiresIn` (in seconds):

| `type`             | When                                                                                                                    |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `connected`        | the tunnel is up for the first time, has `url`                                                                          |
| `reconnecting`     | an attempt failed or the connection dropped, has `error` and `retryIn`; `isKeepAliveTimeout()` identifies a silent drop |
| `reconnected`      | the tunnel is up again, has `url`                                                                                       |
| `banner`           | a message from the server for the user                                                                                  |
| `session_expiring` | the session time limit is near, has `expiresIn`                                                                         |
| `terminated`       | the server closed the tunnel for good, has `reason` and `message`                                                       |
| `local_error`      | the local address is unreachable                                                                                        |
| `error`            | the permanent error that stopped the tunnel                                                                             |

PHP code is synchronous, so events arrive only while `forward()`, `wait()` or `events()` is running.

Network failures are retried indefinitely. The tunnel ends with an exception only when retrying is pointless:

* `Tuna\ServerException`: the API rejected the tunnel, for example a bad key or an unpaid plan; `serverMessage` and `requestId` are there for support;
* `Tuna\TerminatedException`: the server closed the tunnel; `reason` is, for example, `deleted` or `session_limit`;
* `Tuna\TunaException`: the base class; the SDK also throws it when tuna-tiny is not found or fails to start, or when `connectTimeout` expires.

## Behavior worth knowing

* On Windows, `close()` stops tuna-tiny without a signal: the tunnel closes by dropping the connection rather than shutting down cleanly.
* If the PHP process is killed with SIGKILL, tuna-tiny keeps running.
