(PHP 4, PHP 5, PHP 7)

pg_pconnect Établit une connexion PostgreSQL persistante


resource pg_pconnect ( string $connection_string [, int $connect_type ] )

pg_pconnect() retourne une ressource de connexion persistante en cas de succès, ou FALSE en cas d'erreur.

Si un second appel est fait à pg_pconnect() avec le même connection_string comme étant une connexion existante, la connexion existante sera retournée à moins que vous ne passez PGSQL_CONNECT_FORCE_NEW à connect_type.

Pour activer les connexions persistantes, la directive de configuration pgsql.allow_persistent du php.ini doit être mise à "On" (ce qui est sa valeur par défaut). Le nombre maximal de connexions peut être limité grâce à la directive de configuration pgsql.max_persistent dans le fichier php.ini (par défaut, elle vaut -1, c'est à dire pas de limite). Le nombre total de connexions peut être configuré avec la directive pgsql.max_links du fichier php.ini.

pg_close() ne refermera pas les connexions persistantes générées par pg_pconnect().

Liste de paramètres


La chaîne connection_string peut être vide pour utiliser tous les paramètres par défaut ou elle peut contenir un ou plusieurs paramètres de configuration séparés par des espaces. Chaque paramètre de configuration est sous la forme code = valeur. Les espaces autour du signe égal sont optionnels. Pour écrire une valeur vide ou une valeur contenant des espaces, entourez cette valeur avec des apostrophes, par exemple : code = 'une valeur'. Les apostrophes et les antislashs à l'intérieur de la valeur doivent être échappés par un antislash, c'est-à-dire \' et \\.

Les mots-clé actuellement reconnus sont : host, hostaddr, port, dbname, user, password, connect_timeout, options, tty (ignoré), sslmode, requiressl (obsolète, utilisez sslmode) et service. La liste de ces arguments dépend de la version de votre serveur PostgreSQL.


Si PGSQL_CONNECT_FORCE_NEW est passé en argument, alors une nouvelle connexion sera créée, même si la chaîne connection_string est identique à celle de la connexion existante.

Valeurs de retour

Ressource de connexion PostgreSQL en cas de succès, FALSE en cas d'échec.


Exemple #1 Exemple avec pg_pconnect()

// connexion à une base de données nommée "marie"

$dbconn2 pg_pconnect("host=localhost port=5432 dbname=marie");
// connexion à une base de données nommée "marie" sur l'hôte "localhost" sur le port "5432"

$dbconn3 pg_pconnect("host=mouton port=5432 dbname=marie user=agneau password=foo");
// connexion à une base de données nommée "marie" sur l'hôte "mouton" avec un
// nom d'utilisateur et un mot de passe

$conn_string "host=mouton port=5432 dbname=test user=agneau password=bar";
$dbconn4 pg_pconnect($conn_string);
// connexion à une base de données nommée "test" sur l'hôte "mouton" avec un
// nom d'utilisateur et un mot de passe

Voir aussi

add a note add a note

User Contributed Notes 10 notes

dmitri at graphictype dot com
17 years ago
How to reset persistent connections:

killall -USR1 httpd
8 years ago
You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).

If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.

* PGBouncer homepage:

* PostgreSQL pooling article by
Dennis Fogg
9 years ago
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:


Good details:
info at karl-philipp dot de
13 years ago
A contribution to the transaction issue raised by "garrett at bgb dot cc".

In a German book about PostgreSQL in connection with PHP (Cornelia Boenigk, PostgreSQL - Grundlagen, Praxis, Anwendungsentwicklung mit PHP) one can read in chapter 19.3 about persistent connections:
If the page processing aborts and the transaction is not finished yet, the next script using the same persistent connection will be considered as the continuation of the transaction. In particular a lock of a table will persist. The explanation is as follows: After the abort of the script no COMMIT or ROLLBACK was sent to the db server.

The author describes a hint to avoid the scenario above:
You can create a function for resolving transactions and locks erroneously not closed. For invoking the function after execution of a script it has to be registered with the function register_shutdown_function():
herve at elma dot fr
16 years ago
For resetting an apache web server and in same time the persistent connections you may use :
./apachectl graceful
Spiros Ioannou
14 years ago
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
raggaflo at libertysurf dot fr
15 years ago
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
etsysx dot i dot hate dot spam at teleline dot es
15 years ago
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
garrett at bgb dot cc
15 years ago
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?

It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.

As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.
ts at dev dot websafe dot pl
9 years ago
// Using pg_pconnect in a class.
// Why this? Because the manual says:
//   If a second call is made to pg_pconnect() with the same
//   connection_string as an existing connection, the existing
//   connection will be returned unless you pass
//   PGSQL_CONNECT_FORCE_NEW as connect_type.
// This is not always true.
* MyClassA creates a postgresql connection using pg_pconnect
* and stores the resulting resource id to $this->conn
class MyClassA
$this->conn =
                or die(

// Showing current php.ini settings to be sure
// that persistent connections s  are allowed.
// -1 means 'unlimited'
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
'<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
'<br>pgsql.max_links: ' . ini_get('pgsql.max_links');

// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
'host=localhost port=5432' .
' dbname=test user=test password=test';

// Creating 10 MyClassA objects using the same $connection_string
$objArr = Array();
for (
$i = 0; $i < 10; $i++)
$objArr[] = new MyClassA($connection_string);

// Human readable result:
foreach($objArr as $id => $object)
'%s: Object %s: using db %s<br>',
get_class($object), $id, $object->conn

/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
/* ------------------------------------------------------------- */
// Each MyClassA object will use its _own_ database Resource id
To Top