You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置PHP PDO默认Unix Socket以连接PostgreSQL?

能否通过配置PHP、PDO或Apache指定PostgreSQL默认Unix Socket路径?

我正在使用PHP PDO通过Unix Socket本地访问PostgreSQL,当前PostgreSQL监听的Unix Socket路径为:
listening on Unix socket "/tmp/.s.PGSQL.5432"

我按照PHP手册中的写法在PDO连接字符串中指定Socket路径却无法生效,代码如下:
$dsn = "pgsql:host=/tmp;port=5432;dbname=$db";

已知一种可行方案是使用:
$dsn = "pgsql:host=localhost;port=5432;dbname=$db";
但我更倾向于使用更简洁的写法:
$dsn = "pgsql:dbname=$db";
不过该方案执行失败,因为系统默认会在/var/run/postgresql/目录下查找Socket,错误信息如下:

$ curl http://localhost/lamp/index.php
SQLSTATE[08006] [7] connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory

我找到修改php.ini的方法,但该方法仅适用于MySQL,对PostgreSQL无效。

测试代码片段(PHP 8.1.12):

$dsn = "pgsql:dbname=$db";

// make a database connection
return new PDO(
        $dsn,
        $user,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

内容的提问来源于stack exchange,提问作者Big Pete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:47:43