本文介绍了PHP 无法创建到 mongoDB 的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚为什么 PHP 驱动程序无法连接到 mongoDB

I try to figure out why PHP driver can't connect to mongoDB

  • PHP 5.3.16 版(64 位)
  • MongoDB:mongodb-linux-x86_64-2.4.3
  • 操作系统:CentOS 5.2 版(最终版)

  • PHP Version 5.3.16 (64bit)
  • MongoDB: mongodb-linux-x86_64-2.4.3
  • OS: CentOS release 5.2 (Final)

添加链接:mongo ->mongodb-linux-i686-2.4.3

创建data文件夹:mkdir/home/max/mongo/data

启动 mongo:

mongo/bin/mongod --dbpath=mongo/data --fork --logpath/var/wefi/logs/feederliteRC/mongodb.log

一切正常,可以与 mongoVUE 监控工具连接.(来自 Windows7)

All works fine and can connect with mongoVUE monitor tool. (from Windows7)

现在,我尝试从 PHP 连接到 BongoDB:

Now, I try to connect to BongoDB from PHP:

我为 PHP 安装了驱动程序:

I installed driver for PHP:

sudo pecl 安装 mongo

on: php -i |grep mongo 我明白了:

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

我添加到php.ini (nano/etc/php.ini): extension=mongo.so

并重启httpd:/etc/init.d/httpd restart

来自代码:

 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 看到 new Mongo 但我得到异常:连接到 MongoDB 服务器时出错.

PHP sees new Mongo but I get exception: "Error connecting to MongoDB server.

奇怪,mongoDB 可以运行,PHP 驱动程序可以运行,但看不到 mongoDB.

Strange, mongoDB runs, driver for PHP works but it doesn't see mongoDB.

谁能帮帮我,

连接到 MongoDB 服务器时出错,无法连接到:localhost:27017:连接被拒绝"

我需要在 php.ini 中添加平滑处理吗?

Do I need add smoething to php.ini?

推荐答案

我认为您的连接应该是这样的:

I think your connection should be something like this:

$conn = new Mongo("mongodb://localhost");

您也可以更好地使用 MongoClient,因为 Mongo 从 1.3.0 版开始已弃用.

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));

有关更多信息,请参阅 php 手册:http://nl.php.net/manual/en/mongo.connecting.auth.php

See the php manual for some more information:http://nl.php.net/manual/en/mongo.connecting.auth.php

编辑如果 localhost 不起作用,请改用 IP 地址(感谢 Maxim Shoustin)

EDITIf localhost won't work use IP address instead (thanks to Maxim Shoustin)

对于 Mongo,它将是:

For Mongo it will be:

$conn = new Mongo("mongodb://127.0.0.1");

或者如果您使用 MongoClient,它将是这样的:

or if you use MongoClient it will be this:

$m = new MongoClient("mongodb://127.0.0.1", array("username" => $username, "password" => $password));

这篇关于PHP 无法创建到 mongoDB 的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:07