Connect PHP to PostgreSQL with Unix Socket Peer Authentication

PostgreSQL peer authentication checks the operating-system identity of the local client process. For PHP-FPM, that identity is usually the pool user, not the visitor or application username.

Last updated: October 16, 2026.

; PHP connection settings
dsn = "pgsql:host=/var/run/postgresql;port=5432;dbname=appdb"
user = "app_role"

# pg_hba.conf
local   appdb   app_role   peer map=php_app

# pg_ident.conf
php_app   www-data   app_role

The PDO host value is the directory containing the Unix socket, not the socket filename. Reload PostgreSQL after changing authentication files and adapt www-data to the actual PHP-FPM account.

Verify each identity in the chain

The PDO_PGSQL DSN documentation accepts an absolute directory path as the host for a Unix-domain socket. Confirm the server socket directory with SHOW unix_socket_directories. Then determine the PHP process user from the FPM pool configuration or the running process list.

Test with psql as that operating-system user. A successful test as your shell account does not prove that PHP-FPM can authenticate. Also ensure the process can traverse the socket directory and that the database role has CONNECT and the required object privileges.

Keep the peer rule narrow

PostgreSQL processes pg_hba.conf records in order, so place a specific database, role, and peer rule before broader local rules. A map delegates the operating-system-to-database-role mapping to pg_ident.conf. Avoid trust, which removes authentication rather than fixing the mapping.

After editing the files, reload the configuration and inspect the PostgreSQL server log for the exact rejected role, database, and matching rule. If the connection unexpectedly uses TCP, check whether the DSN contains localhost; that selects a network connection instead of the socket directory. Confirm the effective connection inside the session with SELECT current_user, inet_client_addr(). A null client address indicates a Unix-domain socket.

Peer authentication applies only to local connections. Containers, separate application hosts, and TCP connections need another method such as SCRAM with TLS. Continue with cleaning PostgreSQL text input, PostgreSQL RLS with connection pools, and secure PHP database connections.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov