---
title: "Connect with PHP"
description: "Connect a PHP application to Exoscale Managed PostgreSQL with PDO and pdo_pgsql, verify-full TLS and credentials from the environment."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/connect-with-php/
product: "PostgreSQL"
section: product
last_updated: 2026-11-10
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# Connect with PHP

Connect a PHP application to a Managed PostgreSQL service with PDO and the `pdo_pgsql` driver, with TLS certificate verification and credentials read from the environment.

## Prerequisites

You need:

- A running Managed PostgreSQL service.
- The [Exoscale CLI](https://community.exoscale.com/reference/cli/exo/index.md), configured with your API credentials, and `jq`.
- PHP 8.1 or later with the `pdo_pgsql` extension. Check with `php -m` that `pdo_pgsql` is
  listed. On Debian and Ubuntu the package is `php-pgsql`.
- Your client IP address in the service IP filter. See
  [Restrict Connections to a Service](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/restrict-connections/index.md).

`pdo_pgsql` uses libpq, so the SSL modes and error messages are the ones described in
[Connect with psql](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/connect-with-psql/index.md). The
service accepts TLS connections only.

## Retrieve the Credentials and the CA Certificate

```bash
eval "$(exo dbaas show SERVICE_NAME -z ZONE -O json | jq -r '.pg.uri_params | "export PGHOST=\(.host) PGPORT=\(.port) PGDATABASE=\(.dbname) PGUSER=\(.user)"')"
export PGPASSWORD="$(exo dbaas user reveal-secrets SERVICE_NAME avnadmin -z ZONE -O json | jq -r .password)"
exo dbaas ca-certificate -z ZONE > ca.pem
export PGSSLROOTCERT="$PWD/ca.pem"
```

Parameters:

- `SERVICE_NAME`: name of your Managed PostgreSQL service, for example `my-postgresql`.
- `ZONE`: Exoscale zone the service runs in, for example `ch-gva-2`.

The JSON output of `exo dbaas show` does not include the password, which is why the second
command reads it with `exo dbaas user reveal-secrets`.

## Connect

Save the following as `index.php`:

```php
<?php

declare(strict_types=1);

function requiredEnv(string $name): string
{
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Environment variable {$name} is not set");
    }

    return $value;
}

$dsn = sprintf(
    'pgsql:host=%s;port=%s;dbname=%s;sslmode=verify-full;sslrootcert=%s;application_name=%s',
    requiredEnv('PGHOST'),
    requiredEnv('PGPORT'),
    requiredEnv('PGDATABASE'),
    requiredEnv('PGSSLROOTCERT'),
    'exoscale-php-sample'
);

$db = new PDO($dsn, requiredEnv('PGUSER'), requiredEnv('PGPASSWORD'), [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
]);

$info = $db->query('SELECT version(), current_database(), current_user')->fetch();
printf("server:   %s\n", $info['version']);
printf("database: %s\n", $info['current_database']);
printf("user:     %s\n", $info['current_user']);

$tls = $db
    ->query('SELECT version, cipher FROM pg_stat_ssl WHERE pid = pg_backend_pid()')
    ->fetch();
printf("tls:      %s %s\n", $tls['version'], $tls['cipher']);
```

Run it:

```bash
php index.php
```

If `PGSSLROOTCERT` points to the wrong certificate, the connection fails with
`SSL error: certificate verify failed`.

The user and the password are the second and third arguments of the `PDO` constructor, not part
of the DSN, so the password needs no escaping and does not appear in an exception message that
echoes the DSN.

A `pdo_pgsql` DSN separates its parameters with `;` and passes them to libpq. Store the CA
certificate under a path without spaces.

## Work from the Service URI

If your deployment provides a single `PG_URI` variable, for example from
`exo dbaas show SERVICE_NAME -z ZONE --uri`, parse it and rebuild the DSN. The snippet reuses the
`requiredEnv()` function defined above:

```php
<?php

$uri = requiredEnv('PG_URI');
$parts = parse_url($uri);

$dsn = sprintf(
    'pgsql:host=%s;port=%s;dbname=%s;sslmode=verify-full;sslrootcert=%s',
    $parts['host'],
    $parts['port'],
    ltrim($parts['path'] ?? '/defaultdb', '/'),
    requiredEnv('PGSSLROOTCERT')
);

$db = new PDO($dsn, rawurldecode($parts['user']), rawurldecode($parts['pass']), [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
```

`parse_url()` returns the user and password still percent-encoded, hence `rawurldecode()`. The
`sslmode=require` of the URI is dropped on purpose: the rebuilt DSN sets `verify-full`.

## Persistent Connections

Each new connection performs a TLS handshake and counts against the service connection limit.
Under PHP-FPM, persistent connections let each worker reuse its connection across requests:

```php
$db = new PDO($dsn, $user, $password, [
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE    => PDO::ERRMODE_EXCEPTION,
]);
```

Read the server limit with `SHOW max_connections;` and keep the number of PHP-FPM workers
across all your application instances below it, or connect through a server-side pool: see
[Manage Connection Pools](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-connection-pools/index.md).

## Use the pgsql Extension

With the procedural `pgsql` extension, the same libpq parameters go into a space-separated
connection string:

```php
<?php

$conn = pg_connect(sprintf(
    "host=%s port=%s dbname=%s user=%s password=%s sslmode=verify-full sslrootcert=%s",
    getenv('PGHOST'), getenv('PGPORT'), getenv('PGDATABASE'),
    getenv('PGUSER'), getenv('PGPASSWORD'), getenv('PGSSLROOTCERT')
));
```

This form works with the generated passwords of the service. A password you set yourself that
contains spaces or quotes must be quoted in the connection string.

## Related Pages

- [Connect with psql](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/connect-with-psql/index.md)
- [Restrict Connections to a Service](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/restrict-connections/index.md)
- [Manage Connection Pools](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/manage-connection-pools/index.md)
- [PDO_PGSQL in the PHP manual](https://www.php.net/manual/en/ref.pdo-pgsql.php) ↗

