PHP fails to create connection to mongoDB
I think your connection should be something like this:
$conn = new Mongo("mongodb://localhost");
Also you can better use MongoClient because Mongo is DEPRECATED as of version 1.3.0.
$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password));
See the php manual for some more information: http://nl.php.net/manual/en/mongo.connecting.auth.php
EDIT If localhost won't work use IP address instead (thanks to Maxim Shoustin)
For Mongo it will be:
$conn = new Mongo("mongodb://127.0.0.1");
or if you use MongoClient it will be this:
$m = new MongoClient("mongodb://127.0.0.1", array("username" => $username, "password" => $password));
Maxim Shoustin
Enthusiastic full-stack developer with a passion for science, architect and team leader. Strong proponent of open licensing. Love helping people Work at AppsFlyer
Updated on June 04, 2022Comments
-
Maxim Shoustin almost 2 years
I try to figure out why PHP driver can't connect to mongoDB
- PHP Version 5.3.16 (64bit)
- MongoDB: mongodb-linux-x86_64-2.4.3
OS: CentOS release 5.2 (Final)
Added link:
mongo -> mongodb-linux-i686-2.4.3
Created
data
folder:mkdir /home/max/mongo/data
initiated mongo:
mongo/bin/mongod --dbpath=mongo/data --fork --logpath /var/wefi/logs/feederliteRC/mongodb.log
All works fine and can connect with mongoVUE monitor tool. (from Windows7)
Now, I try to connect to BongoDB from PHP:
I installed driver for PHP:
sudo pecl install mongo
on:
php -i | grep mongo
I get:mongo mongo.allow_empty_keys => 0 => 0 mongo.chunk_size => 262144 => 262144 mongo.cmd => $ => $ mongo.default_host => localhost => localhost mongo.default_port => 27017 => 27017 mongo.is_master_interval => 15 => 15 mongo.long_as_object => 0 => 0 mongo.native_long => 0 => 0 mongo.ping_interval => 5 => 5 OLDPWD => /usr/share/pear/doc/mongo _SERVER["OLDPWD"] => /usr/share/pear/doc/mongo
I added to
php.ini
(nano /etc/php.ini
):extension=mongo.so
and restarted
httpd
:/etc/init.d/httpd restart
from code:
try { // open connection to MongoDB server $conn = new Mongo('localhost'); } catch (MongoConnectionException $e) { die('Error connecting to MongoDB server'); } catch (MongoException $e) { die('Error: ' . $e->getMessage()); }
PHP sees
new Mongo
but I get exception:"Error connecting to MongoDB server
.Strange, mongoDB runs, driver for PHP works but it doesn't see mongoDB.
Can someone help me,
[EDIT]
"Error connecting to MongoDB server Failed to connect to: localhost:27017: Connection refused"
Do I need add smoething to
php.ini
?