0
votes

I have installed mongodb on a newly installed Ubuntu 18.04 server, and while I am able to work with mongo on the command line, I cannot seem to connect to it using PHP.

I've been following the process as per https://www.youtube.com/watch?v=RQcQ5tvb5E8&t=620s:

apt install mongodb-server
apt install php-pear # to get PECL
apt install php7.2-dev # to get phpize
pecl install mongodb

phpinfo() shows extension_dir=/usr/lib/php/20170718, and mongodb.so is indeed in that directory, with the same ownership and permissions as all other files. php -i | grep extension_dir shows extension_dir => /usr/lib/php/20170718 => /usr/lib/php/20170718

I then added extension=mongodb.so to /etc/php/7.2/apache2/php.ini, in the same location as the other extensions are listed. There is also a php.ini file under /etc/php/7.2/cli/, so I added the line there to. I then restarted the apache2 service.

I created a test file under /var/www/html/mongo.php

<?php

$m = new Mongo();
var_dump($m);exit;

When I browse to that page I get a 'This page isnt working; HTTP ERROR 500' message in Chrome. I have also tried Mongodb();, MongoClient();, MongodbClient();, mongo();, mongodb();, and mongodbclient();, but all to no avail.

2
Please share the mongo status... sudo systemctl status mongodVikash Pathak

2 Answers

0
votes

Please make sure you have also installed the mongodb php driver. Please confirm the php version first.

On Ubuntu you can just do:

sudo apt-get install php-mongodb

or the same for specific PHP version:

sudo apt-get install php5.6-mongo

or

sudo apt-get install php7.0-mongodb

And then restart the service.

sudo systemctl reload nginx
0
votes

You should to try some of these

https://docs.mongodb.com/ecosystem/drivers/php/

https://www.php.net/manual/en/mongodb.tutorial.library.php

they should work fine with php7 + composer

Actually with composer is pretty easy(something like this):

`$ composer require mongodb/mongodb
 ./composer.json has been created
 Loading composer repositories with package information
 Updating dependencies (including require-dev)
   - Installing mongodb/mongodb (1.0.0)
     Downloading: 100%         

 Writing lock file
 Generating autoload files

Create a File: test.php (in the same location where you ran composer)

<?php
 require 'vendor/autoload.php'; // include Composer's autoloader
 $client = new MongoDB\Client("mongodb://localhost:27017");
 $collection = $client->demo->beers;
 $result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
 echo "Inserted with Object ID '{$result->getInsertedId()}'";
 ?>

That should be enough