Setting Up MongoDB with PHP and MAMP
Getting MongoDB working with PHP and MAMP was a bit tricky for me, so hopefully this guide will save you some frustration.
At the end of this tutorial I've included a section with a few possible issues you might run into and their solutions.
This tutorial assumes you already have MAMP running on your Mac. Also, you may need to preface some commands with
sudo to get them to run.
1) Install Homebrew
You're going to need a package manager. I recommend Homebrew:
2) Install MongoDB
First you must add
/usr/local/bin to the beginning of the
$PATH in Terminal (learn more about this here):
Then install Mongo:
3) Install the PHP MongoDB driver
First, add MAMP's
/bin directory to the beginning of the
$PATH, obviously replacing php5.x.x with your version of PHP:
Then go into that directory:
Now that you're here, you can use Pear to install the PHP MongoDB driver (see the bottom of this post if you get the
‘make’ failed error):
4) Edit php.ini
extension=mongo.so to your /Applications/MAMP/bin/php/php5.x.x/conf/php.ini file.
5) Restart MAMP
This is a simple one. Just stop and then restart MAMP from via the MAMP interface.
6) Start MongoDB
In Terminal enter mongod to start Mongo. You can access the Mongo shell by entering mongo into a new Terminal window.
7) Test PHP script
Now that everything is installed, create a PHP script with the following code in it and test it in the browser:
If you see the database record outputted and there aren't any errors then you've successfully set up MongoDB with PHP and MAMP!
Fixing the 'make' failed error
You may have gotten this error when trying to install the PHP MongoDB driver. Here are a few possible causes and their solutions:
1) Xcode is missing Command Line Tools If you don't have Xcode installed then go ahead and install it. Open it and go to Preferences > Downloads. Install the Command Line Tools and then try the install again:
2) MAMP is missing certain PHP files MAMP doesn't come installed with all of PHP's extra extensions and modules, some of which we may need. To get these files, go to http://www.php.net/downloads.php and download PHP.
Once you've decompressed the archive, copy all of the files into /Applications/MAMP/bin/php/php5.x.x/include/php (create the /include and /php directories if they don't exist).
Now navigate to that directory in Terminal and run the configuration:
Once that finishes, try the install again:
If the install now works then go to Step 4 to proceed.
Posted on June 13th, 2013