# Connecting to SurrealDB

Open a connection to a SurrealDB instance with version 2 of the PHP SDK, select a namespace and database, and configure reconnection.

Before you can run queries, you open a connection to a SurrealDB instance. You create a `Surreal` instance and call `connect()` with a connection string and a set of options. The options carry the namespace, database, authentication, and reconnection settings.

## API references

<table>
    <thead>
        <tr>
            <th scope="col">Method</th>
            <th scope="col">Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td scope="row" data-label="Method"><a href="/docs/reference/php/v2/api/core.md#connect"> <code> $db->connect($url, $options) </code></a></td>
            <td scope="row" data-label="Description">Connects to a local or remote database endpoint</td>
        </tr>
        <tr>
            <td scope="row" data-label="Method"><a href="/docs/reference/php/v2/api/core.md#close"> <code> $db->close() </code></a></td>
            <td scope="row" data-label="Description">Closes the connection to the database</td>
        </tr>
        <tr>
            <td scope="row" data-label="Method"><a href="/docs/reference/php/v2/api/core.md#use"> <code> $db->use($namespace, $database) </code></a></td>
            <td scope="row" data-label="Description">Switches to a specific namespace and database</td>
        </tr>
        <tr>
            <td scope="row" data-label="Method"><a href="/docs/reference/php/v2/api/core.md#status"> <code> $db->status() </code></a></td>
            <td scope="row" data-label="Description">Returns the current connection status</td>
        </tr>
    </tbody>
</table>

## Opening a connection

Create a `Surreal` instance, then call `connect()` with a connection string and a [`ConnectOptions`](/docs/reference/php/v2/api/core.md#connectoptions) object.

```php
use SurrealDB\SDK\Surreal;
use SurrealDB\SDK\Connection\ConnectOptions;
use SurrealDB\SDK\Auth\RootAuth;

$db = new Surreal();

$db->connect('ws://127.0.0.1:8000/rpc', new ConnectOptions(
    namespace: 'surrealdb',
    database: 'docs',
    authentication: new RootAuth('root', 'root'),
));
```

### Connection string

The connection string is a URI pointing to a SurrealDB instance. Version 2 supports two transports:

- **WebSocket** (`ws://`, `wss://`) for long-lived connections that support live queries and server-side transactions.
- **HTTP** (`http://`, `https://`) for stateless, short-lived requests.

```php
// WebSocket, local
$db->connect('ws://127.0.0.1:8000/rpc');

// HTTP, local
$db->connect('http://127.0.0.1:8000/rpc');

// WebSocket, remote
$db->connect('wss://cloud.surrealdb.com');
```

The SDK appends `/rpc` to the path if you leave it out, so `ws://127.0.0.1:8000` and `ws://127.0.0.1:8000/rpc` are equivalent.

> [!NOTE]
> Version 2 does not include the embedded engines available in some other SDKs. Connect to a running SurrealDB instance over WebSocket or HTTP.

### Connection options

`ConnectOptions` configures the connection. Every argument is optional.

| Option | Type | Description |
|--------|------|-------------|
| `namespace` | `?string` | Namespace to select on connect |
| `database` | `?string` | Database to select on connect |
| `authentication` | `Credentials \| Token \| string \| Closure \| null` | Credentials or a token used to authenticate, and to re-authenticate after a reconnect |
| `versionCheck` | `bool` | Check the server version on connect (default `true`) |
| `invalidateOnExpiry` | `bool` | Invalidate the session when its token expires instead of renewing it (default `false`) |
| `reconnect` | `bool \| ReconnectStrategyInterface` | Reconnection behaviour for WebSocket connections (default `true`) |

### Authentication details

Passing credentials to `connect()` is the preferred way to authenticate, because it lets the SDK re-authenticate automatically when a WebSocket connection drops and reconnects. You can also pass a token, or a closure that returns credentials. See [Authentication](/docs/reference/php/v2/concepts/authentication.md) for the credential types.

### Reconnection behaviour

For WebSocket connections, the SDK reconnects automatically if the connection is lost. Set `reconnect` to `false` to disable this, leave it as `true` for the defaults, or pass a `ReconnectStrategyInterface` such as `ExponentialBackoffReconnect` to control the backoff.

```php
use SurrealDB\SDK\Reconnect\ExponentialBackoffReconnect;

$db->connect('ws://127.0.0.1:8000/rpc', new ConnectOptions(
    reconnect: new ExponentialBackoffReconnect(),
));
```

## Selecting a namespace and database

You can select the namespace and database on connect, or switch later with `use()`. Pass a namespace and an optional database.

```php
$db->use('surrealdb', 'docs');
```

The SDK emits a `using` event whenever the namespace or database changes, including on the initial connection.

## Connection status

The `status()` method returns a [`ConnectionStatus`](/docs/reference/php/v2/api/core.md#connectionstatus) enum with one of four values:

- `Disconnected` when there is no connection
- `Connecting` when a connection is being opened
- `Connected` when the SDK is ready to run queries
- `Reconnecting` when the connection dropped and the SDK is reconnecting

```php
use SurrealDB\SDK\Connection\ConnectionStatus;

if ($db->status() === ConnectionStatus::Connected) {
    // ready to query
}

// Shorthand for the check above
if ($db->isConnected()) {
    // ready to query
}
```

You can also subscribe to lifecycle events to react to status changes.

```php
$db->subscribe('connected', function (string $version): void {
    echo "Connected to SurrealDB {$version}";
});
```

The available events are `connecting`, `connected`, `reconnecting`, `disconnected`, `error`, `auth`, and `using`. The `subscribe()` method returns a closure that removes the listener when called.

## Closing a connection

Call `close()` when you are done. This releases the connection and its resources.

```php
$db->close();
```

## Checking the server

The `health()` method throws if the instance is unreachable, and `version()` returns the server version string.

```php
$db->health();

echo $db->version(); // "surrealdb-2.1.0"
```

## Testing for features

Some features depend on the transport or the server version. Use `isFeatureSupported()` to check before relying on one.

```php
use SurrealDB\SDK\Protocol\Features;

if ($db->isFeatureSupported(Features::liveQueries())) {
    // safe to run a live query
}
```

## Learn more

- [Surreal API reference](/docs/reference/php/v2/api/core.md) for the full connection interface
- [Authentication](/docs/reference/php/v2/concepts/authentication.md) for signing in and managing credentials
- [Error handling](/docs/reference/php/v2/concepts/error-handling.md) for connection and version errors
