PHP 8.4.1 Released!

pg_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_connectPostgreSQL 接続をオープンする

説明

pg_connect(string $connection_string, int $flags = 0): PgSql\Connection|false

pg_connect() は、connection_string で指定された情報を用いてデータベースとの接続をオープンします。

同じ connection_string 引数で 2 回 pg_connect() 関数がコールされた場合は、 flagsPGSQL_CONNECT_FORCE_NEW を指定していない限り 既存の接続が返されます。

複数のパラメータをサポートする古い構文 $conn = pg_connect("host", "port", "options", "tty", "dbname") は推奨されません。

パラメータ

connection_string

すべてデフォルトのパラメータを使用する場合には connection_string を空にすることが可能です。 または 1 つ以上のパラメータを空白で区切って指定することも可能です。 個々のパラメータは keyword = value の形式で 設定します。等号の前後の空白はあってもなくてもかまいません。 空の値や空白を含む値を指定する場合は、その値をシングルクォートで 囲みます(例: keyword = 'a value')。値の中に シングルクォートやバックスラッシュが含まれる場合は、それらを バックスラッシュでエスケープする必要があります(例: \' および \\)。

現在利用できるパラメータは以下のとおりです。 host, hostaddr, port, dbname (デフォルトは user の値), user, password, connect_timeout, options, tty(無視されます), sslmode, requiressl(非推奨。代わりに sslmode を推奨します) および service 。これらのうち実際にどの パラメータが使えるかは、PostgreSQL のバージョンに依存します。

options パラメータを使うと、 サーバー側で実行されるコマンドラインパラメータを指定することができます。

flags

PGSQL_CONNECT_FORCE_NEW が渡された場合は、 たとえ connection_string が既存の接続と まったく同一であっても新しい接続をオープンします。

PGSQL_CONNECT_ASYNC を指定すると、 非同期接続を確立します。この接続の状態は、 pg_connect_poll() あるいは pg_connection_status() で確認できます。

戻り値

成功した場合に PgSql\Connection クラスのインスタンスを返します。 失敗した場合に false を返します

変更履歴

バージョン 説明
8.1.0 PgSql\Connection クラスのインスタンスを返すようになりました。 これより前のバージョンでは、 リソース を返していました。

例1 pg_connect() の使用法

<?php
$dbconn
= pg_connect("dbname=mary");
// "mary"という名前のデータベースに接続

$dbconn2 = pg_connect("host=localhost port=5432 dbname=mary");
// "localhost"のポート"5432"にて"mary"という名前のデータベースに接続

$dbconn3 = pg_connect("host=sheep port=5432 dbname=mary user=lamb password=foo");
// ユーザー名とパスワードを指定してホスト"sheep"上の"mary"という名前のデータベースに接続

$conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";
$dbconn4 = pg_connect($conn_string);
// ユーザー名とパスワードを指定してホスト"sheep"上の"test"という名前のデータベースへ接続

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
// "localhost" のデータベースに接続する際に、エンコーディングを UTF-8 に指定
?>

参考

  • pg_pconnect() - 持続的な PostgreSQL 接続をオープンする
  • pg_close() - PostgreSQL 接続をクローズする
  • pg_host() - 接続に関連するホスト名を返す
  • pg_port() - 接続に関連するポート番号を返す
  • pg_tty() - 接続に関する TTY 名を返す
  • pg_options() - 接続に関連するオプションを取得する
  • pg_dbname() - データベース名を取得する

add a note

User Contributed Notes 20 notes

up
13
lukasz dot wolczak at gmail dot com
8 years ago
It is worth to know, that you can set application_name in connection string, consider this simple example:

<?php
$appName
= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$connStr = "host=localhost port=5432 dbname=postgres user=postgres options='--application_name=$appName'";

//simple check
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from pg_stat_activity");
var_dump(pg_fetch_all($result));

?>

By doing this move on cli or cgi you can see in pgAdmin what scripts are running or what requests are running on database. You can extend configuration of postgres to track slow queries and print application name to logs. It was very usuful to me to find out what and where should I optimize.
up
6
Dave
11 years ago
If you use pgbouncer and unix socket
and you pgbouncer.ini looks like this
listen_port = 6432
unix_socket_dir = /tmp

you connect like this

pg_connect('host=/tmp port=6432 dbname=DB user=USER password=PASS');
up
4
Anonymous
10 years ago
Getting md5 passwords was confusing because of a lack of documentation:

- set up your pg_hba.conf in order to use md5 password instead of 'trust' or 'ident'
- check if your postgres.conf has 'password_encryption=on' (depending on the version this might already be 'on').
- make sure to restart your postgres process.
- in PHP you just supply the username and password in _plain_ text:
'host=localhost port=5432 dbname=megadb user=megauser password=holyhandbagsbatmanthispasswordisinplaintext'
The postgres PHP library will automagically do the md5 encoding for you, no need to do it yourself.
up
3
bgalloway at citycarshare dot org
16 years ago
Beware about writing something like
<?php
function getdb_FAILS() {
return
pg_connect("...") or die('connection failed');
}
?>

It will return a boolean. This will appear to be fine if you don't use the return value as a db connection handle, but will fail if you do.

Instead, use:
<?php
function getdb() {
$db = pg_connect("...") or die('connection failed');
return
$db;
}
?>

which actually returns a handle.
up
2
tim at buttersideup dot com
16 years ago
It's not explicitly stated here, but you can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty. This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied... Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
up
2
thakur at corexprts dot com
14 years ago
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

<?php
$d
=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
?>
up
1
matias at nospam dot projectcast dot com
22 years ago
At least with Postgres 7.2, connecting to local postgresdatabase requires a user in the database with the same name as the user running apache, or the connection fails.
up
0
VLroyrenn
5 years ago
For what it's worth, it should be noted that, while PHP will generally handle connection-reuse for you so long as you keep using the same connection strings, as in the following example:

<?php
$before_conn1
= microtime(true);
$db1 = pg_connect($conn_string);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo(
$before_conn2 - $before_conn1); // Takes ~0.03s
echo("\n");
echo(
$after_conn2 - $before_conn2); // Takes 0s
?>

...as nice as it would have been, this does not hold true for async connections; you have to manage those yourself and you can't follow up an async connection with a blocking one later on as an easy way to wait for the connection process to complete before sending queries.

<?php
$before_conn1
= microtime(true);
$db1 = pg_connect($conn_string, PGSQL_CONNECT_ASYNC);
sleep(1);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo(
$before_conn2 - $before_conn1); // Takes ~1s
echo("\n");
echo(
$after_conn2 - $before_conn2); // Takes ~0.025s
?>
up
-1
Anonymous
19 years ago
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
up
-1
gutostraube at gmail dot com
15 years ago
It's possible connect to a PostgreSQL database via Unix socket using the pg_connect() function by the following two ways:

1) Using the socket path:

<?php
$conn
= pg_connect('host=/var/run/postgresql user=username dbname=databasename');
?>

2) Omitting the host name/path:

<?php
$conn
= pg_connect('user=username dbname=databasename');
?>

Note: in this case (omitting the host value), the default socket path will be used.
up
-2
leace at post dot cz
24 years ago
If you use PostgreSQL users for authenticating into your pg database rather than using your own authentication, always specify host directive in pg_connect and edit pg_hba.conf to authenticate from this host accordingly. Otherwise, PHP will connect as 'local' using UNIX domain sockets, which is set in pg_hba.conf to 'trust' by default (so you can connect using psql on console without specifying password) and everyone can connect to db _without password_ .
up
-2
phpnet at benjamin dot schulz dot name
20 years ago
if you need to open a new connection handle (i.e. for multiple pg_send_query()) use PGSQL_CONNECT_FORCE_NEW as second parameter to pg_connect()
up
-2
floriparob at gmail dot com
8 years ago
Using the "service" parameter as the connection string -- we found that the following functions:-

putenv("PGSERVICEFILE=/path/to/your/service/file/pg_service.conf");
$connect_string = ("service=testdb");
try {
$pgconn_handle = pg_connect($connect_string);
. . . . . etc.

Note:-
1) the environment variable has to point to the path AND file name.
2) the file has to be readable by Apache.

See:-

https://www.postgresql.org/docs/9.6/static/libpq-pgservice.html

for how to create your pg_service.conf
up
-3
Sohel Taslim
17 years ago
I got the same problem but I have to solve that in different way.
In my postgresql.conf file the following was commented.
So, I active that under Connection Settings-

# - Connection Settings –
tcpip_socket = true
up
-2
xzilla at users dot sourceforge dot net
20 years ago
regarding the note from matias at nospam dot projectcast dot com
on 12-Feb-2002 01:16, you do not need a user in the database with the same name a your web user with ANY version of postgresql. The only time that would be a requirement ifs if you set your postgresql server to only allow IDENT based authentication (which IIRC is the default on Red Hat systems, which might be what lead to the confusion). For more info on the various authentication methods allowed by postgresql, check out http://www.postgresql.org/docs/7.4/static/client-authentication.html
up
-2
jtate at php dot net
21 years ago
If you use host=HOSTNAME in your pg_connect string when connecting to PostgreSQL databases newer than 7.1, you need to make sure that your postmaster daemon is started with the "-i" option. Otherwise the connection will fail. See http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
up
-3
kayotix at yahoo dot com
24 years ago
Little note that is buried in the install somewhere. In Php 3, PostgreSQL support was activated by adding --with-postgresql=[DIR] to the options passed to ./configure. With Php 4.0.2 (on Linux) the parameter was --with-pgsql. The only place I found this was in the installing PHP on Unix section of the manual.
up
-3
rolf at sir-wum dot de
23 years ago
pg_connect() won't work with the authentication method 'crypt' in the pg_hba.conf. Took me an hour to figure that out till I remeberd some other issues with windows missing the crypt() call.
up
-5
derry at siliconriver.com dot au
21 years ago
pg_connect seems to support SSL connections, on systems where Postgres has been compiled with ssl, i'm assuming this is since psql uses libpq to connect.
pg_connect can successfully connect, and use the "requiressl" argument.
up
-5
borovik -at- gmail
17 years ago
"If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
"
I solved this error just by setting listen_addresses = '*' in the postgresql.conf file. This error occurs probably despite of a name resolution to localhost, given in the "host" parameter. So you can set the host in the pg_connect() function.
To Top