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, configured with your API credentials, and
jq. - PHP 8.1 or later with the
pdo_pgsqlextension. Check withphp -mthatpdo_pgsqlis listed. On Debian and Ubuntu the package isphp-pgsql. - Your client IP address in the service IP filter. See Restrict Connections to a Service.
pdo_pgsql uses libpq, so the SSL modes and error messages are the ones described in
Connect with psql. The
service accepts TLS connections only.
Retrieve the Credentials and the CA Certificate
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 examplemy-postgresql.ZONE: Exoscale zone the service runs in, for examplech-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
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:
php index.phpIf 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
$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:
$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.
Use the pgsql Extension
With the procedural pgsql extension, the same libpq parameters go into a space-separated
connection string:
<?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.