Firestore插入数据时出现ERR_CONNECTION_RESET错误求助
问题描述
向Firestore插入数据时触发ERR_CONNECTION_RESET错误,代码中已确认Firestore连接建立成功(输出1),但执行set()方法时崩溃。使用的Laravel代码如下:
<?php use Illuminate\Support\Facades\Route; use Kreait\Firebase\Factory; Route::get('/', function () { return view('welcome'); }); Route::get('/insert', function () { try { $firestore = app('firebase.firestore')->database(); if ($firestore) { echo '1'; } else { echo '0'; } $stuRef = $firestore->collection('users')->newDocument(); $stuRef->set([ 'email' => 'test2@test.ru', 'password' => 'test2' ]); return "inserted"; } catch (\Exception $e) { echo $e->getMessage(); } }); Route::get('/test', function () { try { return "ok"; } catch (\Exception $e) { echo $e->getMessage(); } });
已完成排查:
- 访问密钥配置正确
- 本地防火墙已关闭
- 部署在XAMPP本地环境,无远程服务器网络限制
- Firestore数据库规则设置为允许所有人读写
- 测试
file_get_contents访问Google官网正常:
Route::get('/test', function () { try { echo file_get_contents('https://www.google.com'); return "ok"; } catch (\Exception $e) { echo $e->getMessage(); } });
解决方案
1. 校验SDK与PHP版本兼容性
Kreait Firebase PHP SDK对PHP版本有严格要求,比如v6.x需要PHP 7.4+,v7.x需要PHP 8.0+。如果XAMPP的PHP版本过低,会导致底层HTTP请求异常:
- 执行
php -v查看当前PHP版本 - 对照SDK版本说明确认兼容性,必要时升级PHP或降级SDK版本
2. 确保cURL扩展启用并正常工作
虽然file_get_contents能访问Google,但Firestore API依赖更复杂的HTTP请求处理,SDK默认使用cURL:
- 打开XAMPP的
php.ini,确保extension=curl未被注释 - 重启Apache服务,通过
phpinfo()确认cURL扩展已加载
3. 临时禁用SSL验证排查证书问题(仅测试用)
本地环境可能存在SSL证书信任问题,导致Firestore连接握手失败:
- 修改Firestore初始化代码,添加SSL配置:
$firestore = (new Factory) ->withServiceAccount(storage_path('app/firebase/service-account.json')) ->withHttpClient(new \GuzzleHttp\Client([ 'verify' => false, ])) ->createFirestore() ->database();
如果测试有效,说明是本地SSL证书问题,可下载Google根证书并配置到PHP的curl.cainfo路径。
4. 检查服务账号权限
即使数据库规则开放,服务账号可能缺少Firestore操作权限:
- 登录Firebase控制台,进入「项目设置」→「服务账号」
- 确保当前服务账号拥有「Cloud Datastore User」或「Editor」角色
- 重新生成服务账号密钥,替换本地配置文件
5. 调整PHP超时与内存限制
插入数据的HTTP请求可能因超时或内存不足被中断:
- 修改
php.ini中的参数:
max_execution_time = 60 memory_limit = 256M
- 重启Apache后重试
内容的提问来源于stack exchange,提问作者lxsenju




