更新时间:2026-05-27 GMT+08:00
PHP示例
操作场景
DDS支持通过PHP语言接口来操作数据,通过PHP连接实例的方式有开启SSL认证连接和关闭SSL认证连接两种,其中开启SSL证书连接加密功能,具有更高的安全性。
DDS新实例默认关闭SSL数据加密,开启SSL请参考开启SSL。
本章节主要介绍使用PHP语言连接副本集实例的方法。
前提条件
驱动获取及使用
PHP驱动相关信息:https://www.php.net/mongodb-driver-manager.construct
开启和关闭SSL安全连接
- 使用MongoDB\Client::__construct()创建client实例。
function __construct( ?string $uri = null, array $uriOptions = [], array $driverOptions = [] )
- 通过$uriOptions设置SSL为true,启用SSL连接。通过$driverOptions设置ca_file为CA证书路径,allow_invalid_hostname设置为true。
<?php require 'vendor/autoload.php'; // include Composer goodies $replicaset_url = 'mongodb://rwuser:*****@192.168.***.***:8635,192.168.***.***:8635/test?authSource=admin&replicaSet=replica'; $test_db = 'test_db'; $test_coll = 'test_coll'; // 创建mongoclient。 $client = new MongoDB\Client( $replicaset_url, [ 'ssl' => true, ], [ "ca_file" => "/path/to/ca.pem", "allow_invalid_hostname" => true ] ); $collection = $client->$test_db->$test_coll; // 插入一条记录。 $result = $collection->insertOne([ 'username' => 'admin', 'email' => 'admin@example.com', ]); echo "Object ID: '{$result->getInsertedId()}'", "\n"; // 查询记录。 $result = $collection->find(['username' => 'admin']); foreach ($result as $entry) { echo $entry->_id, ': ', $entry->email, "\n"; } ?>
<?php
require 'vendor/autoload.php'; // include Composer goodies
$replicaset_url = 'mongodb://rwuser:*****@192.168.***.***:8635,192.168.***.***:8635/test?authSource=admin&replicaSet=replica';
$test_db = 'test_db';
$test_coll = 'test_coll';
// 创建mongoclient。
$client = new MongoDB\Client($replicaset_url);
$collection = $client->$test_db->$test_coll;
// 插入一条记录。
$result = $collection->insertOne([
'username' => 'admin',
'email' => 'admin@example.com',
]);
echo "Object ID: '{$result->getInsertedId()}'", "\n";
// 查询记录。
$result = $collection->find(['username' => 'admin']);
foreach ($result as $entry) {
echo $entry->_id, ': ', $entry->email, "\n";
}
?>
- URL中的认证数据库必须为“admin”,即“authSource=admin”。
- rwuser账户的认证数据库必须为“admin”,之后再切换至业务数据库。