Why does PHP 8.0 remove the +srv?

I had an issue which I maanged to eventually solve myself.

More info at: mongodb - PHP Mongo Bulk Write - Stack Overflow

In short PHP 8.0 removes the +srv from the connection string.
Where as, PHP 7.4 keeps it.

Why is the PHP 8.0 driver doing this? I assume because I found the wrong syntax or something and that it’s not easy to find the write usage with PHP due to the new nature of PHP 8.0. I really would like to know how do do this in PHP 8.0.

The script to save you going to the above link is

<?php
use MongoDB\Client;
use MongoDB\Driver\ServerApi;
echo extension_loaded("mongodb") ? "loaded\n" : "not loaded\n";
$uri = 'mongodb+srv://user:password@xxxxx.yyyy.mongodb.net/?retryWrites=true&w=majority';
$manager = new MongoDB\Driver\Manager($uri);
print_r($manager);
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('TestyDB.TestyCollection', $bulk);

$filter = ['x' => ['$gt' => 1]];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['x' => -1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('TestyDB.TestyCollection', $query);

foreach ($cursor as $document) {
    var_dump($document);
}

?>

See my response in the Stack Overflow thread. I addressed various lines from your original question in detail. I think you were just misunderstanding how a driver processes a mongodb+srv:// URI.

Regarding the original ConnectionTimeoutException

It looks like you edited your Stack Overflow answer shortly after creating this thread to note:

I contacted my hosting company support about this. They opened the port on 27017 and this script now works with PHP 8.0 and 7.4

That would have explained the original connection error you were seeing. I found no evidence of a driver issue or any behavioral differences between PHP 7.4 and 8.0.

2 Likes