Connecting
PHP Manual

Connecting over SSL

The driver supports connecting to » MongoDB over SSL and can optionally use SSL Stream Context options to provide more details, such as verifying certificates against specific certificate chain, or authenticate to » MongoDB using X509 certificates.

Example #1 Connect to MongoDB Instance with SSL Encryption

<?php
$mc 
= new MongoClient("mongodb://server1", array("ssl" => true));
?>

Example #2 Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is

<?php
$ctx 
stream_context_create(array(
    
"ssl" => array(
        
/* Optionally verify the server is who he says he is, and has been certified by CA we trust */
        
"verify_peer"       => true,
        
"allow_self_signed" => false,
        
"cafile"            => "/vagrant/certs/ca.pem",
    ),
));

$mc = new MongoClient(
    
"mongodb://server1"
    array(
"ssl" => true), 
    array(
"context" => $ctx)
);
?>

Example #3 Connect to MongoDB Instance that Requires Client Certificates

<?php
$ctx 
stream_context_create(array(
    
"ssl" => array(
        
"local_cert" => "/vagrant/certs/client.pem",
        
/* If the certificate we are providing was passphrase encoded, we need to set it here */
        
"passphrase" => "My Passphrase for the local_cert",

        
/* Optionally verify the server is who he says he is */
        
"verify_peer" => true,
        
"cafile"      => "/vagrant/certs/ca.pem",
    ),
));

$mc = new MongoClient(
    
"mongodb://server1/?ssl=true"
    array(), 
    array(
"context" => $ctx)
);
?>

Example #4 Authenticating with X.509 certificates

The username is the certificate subject from the X509, which can be extracted like this:

openssl x509 -in /vagrant/certs/ca-signed-client.pem -inform PEM -subject -nameopt RFC2253
<?php
$ctx 
stream_context_create( array(
    
"ssl" => array(
        
"local_cert" => "/vagrant/certs/ca-signed-client.pem",
    )
) );

$mc = new MongoClient(
    
'mongodb://username@server1/?authSource=$external&authMechanism=MONGODB-X509&ssl=true'
    array(), 
    array(
"context" => $ctx)
);
?>

Where username is the certificate subject.

Log delle modifiche

Versione Descrizione
1.5.0 Added support for X509 authentication.
1.4.0 Added support for connecting to SSL enabled MongoDB.

Connecting
PHP Manual