Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
PHP
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
PHPchevron-right

Getting Set Up to Run PHP With MongoDB

Michael Lynn12 min read • Published Feb 05, 2022 • Updated Aug 29, 2024
MongoDBPHP
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
PHP badge
Welcome to this quickstart guide for MongoDB with PHP. I know you're probably excited to get started writing code and building applications using PHP with MongoDB. We'll get there, I promise. Let's go through some necessary set-up first, however.
This guide is organized into a few sections over a few articles. This first article addresses the installation and configuration of your development environment. PHP is an integrated web development language. There are several components you typically use in conjunction with the PHP programming language. If you already have PHP installed and you simply want to get started with PHP and MongoDB, feel free to skip to the next article in this series.
Let's start with an overview of what we'll cover in this series.
A brief note on PHP and Apache: Because PHP is primarily a web language — that is to say that it's built to work with a web server — we will spend some time at the beginning of this article ensuring that you have PHP and the Apache web server installed and configured properly. There are alternatives, but we're going to focus on PHP and Apache.
PHP was developed and first released in 1994 by Rasmus Lerdorf. While it has roots in the C language, PHP syntax looked much like Perl early on. One of the major reasons for its massive popularity was its simplicity and the dynamic, interpreted nature of its implementation.

Prerequisites

You'll need the following installed on your computer to follow along with this tutorial:
  • MacOS Catalina or later: You can run PHP on earlier versions but I'll be keeping to MacOS for this tutorial.
  • Homebrew Package Manager: The missing package manager for MacOS.
  • PECL: The repository for PHP Extensions.
  • A code editor of your choice: I recommend Visual Studio Code.

Installation

First, let's install the command line tools as these will be used by Homebrew:
1xcode-select --install
Next, we're going to use a package manager to install things. This ensures that our dependencies will be met. I prefer Homebrew, or brew for short. To begin using brew, open your terminal app and type:
1/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
This leverages curl to pull down the latest installation scripts and binaries for brew.
The installation prompts are fairly straightforward. Enter your password where required to assume root privileges for the install. When it's complete, simply type the following to verify that brew is installed correctly:
1brew --version
If you experience trouble at this point and are unable to get brew running, visit the Homebrew installation docs.
You can also verify your homebrew installation using brew doctor. Confirm that any issues or error messages are resolved prior to moving forward. You may find warnings, and those can usually be safely ignored.

Installing Apache

To use MongoDB with PHP, we must install Apache.
The latest macOS 11.0 Big Sur comes with Apache 2.4 pre-installed but Apple removed some critical scripts, which makes it difficult to use.
So, to be sure we're all on the same page, let's install Apache 2.4 via Homebrew and then have it to run on the standard ports (80/443).
When I was writing this tutorial, I wasted a lot of time trying to figure out what was happening with the pre-installed version. So, I think it's best if we install from scratch using Homebrew.
1sudo apachectl stop # stop the existing apache just to be safe
2sudo launchtl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist # Remove the configuration to run httpd daemons
Now, let's install the latest version of Apache:
1brew install httpd
Once installed, let's start up the service.
1brew services start httpd
You should now be able to open a web browser and visit http://localhost:8080 and see something similar to the following:
"It works" while installing Apache to Use MongoDB with PHP
The standard Apache web server doesn't have support for PHP built in. Therefore, we need to install PHP and the PHP Extension to recognize and interpret PHP files.

Installing PHP

If you've installed previous versions of PHP, I highly recommend that you clean things up by removing older versions. If you have previous projects that depend on these versions, you'll need to be careful, and back up your configurations and project files.
Homebrew is a good way for MacOS users to install PHP.
1brew install php
Once this completes, you can test whether it's been installed properly by issuing the following command from your command-line prompt in the terminal.
1php --version
You should see something similar to this:
1$ php --version
2PHP 8.0.0 (cli) (built: Nov 30 2020 13:47:29) ( NTS )
3Copyright (c) The PHP Group
4Zend Engine v4.0.0-dev, Copyright (c) Zend Technologies
5with Zend OPcache v8.0.0, Copyright (c), by Zend Technologies

Installing the PHP extension

Now that we have php installed, we can configure Apache to use PHP to interpret our web content, translating our php commands instead of displaying the source code.
PECL (PHP Extension Community Library) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities or the downloading and development of PHP extensions. pecl is the binary or command-line tool (installed by default with PHP) you can use to install and manage PHP extensions. We'll do that in this next section.
Install the PHP MongoDB extension before installing the PHP Library for MongoDB. It's worth noting that full MongoDB driver experience is provided by installing both the low-level extension (which integrates with our C driver) and high-level library, which is written in PHP.
You can install the extension using PECL on the command line:
1pecl install mongodb
Next, we need to modify the main php.ini file to include the MongoDB extension. To locate your php.ini file, use the following command:
1$ php --ini
2Configuration File (php.ini) Path: /usr/local/etc/php/8.3
To install the extension, copy the following line and place it at the end of your php.ini file.
1extension=mongodb.so
After saving php.ini, restart the Apache service and to verify installation, you can use the following command.
1brew services restart httpd
2
3php -i | grep mongo
You should see output similar to the following:
1$ php -i | grep mongo
2mongodb
3libmongoc bundled version => 1.25.2
4libmongoc SSL => enabled
5libmongoc SSL library => OpenSSL
6libmongoc crypto => enabled
7libmongoc crypto library => libcrypto
8libmongoc crypto system profile => disabled
9libmongoc SASL => enabled
10libmongoc SRV => enabled
11libmongoc compression => enabled
12libmongoc compression snappy => enabled
13libmongoc compression zlib => enabled
14libmongoc compression zstd => enabled
15libmongocrypt bundled version => 1.8.2
16libmongocrypt crypto => enabled
17libmongocrypt crypto library => libcrypto
18mongodb.debug => no value => no value
You are now ready to begin using PHP to manipulate and manage data in your MongoDB databases. Next, we'll focus on getting your MongoDB cluster prepared.

Troubleshooting your PHP configuration

If you are experiencing issues with installing the MongoDB extension, there are some tips to help you verify that everything is properly installed.
First, you can check that Apache and PHP have been successfully installed by creating an info.php file at the root of your web directory. To locate the root web directory, use the following command:
1$ brew info httpd
2==> httpd: stable 2.4.58 (bottled)
3Apache HTTP server
4https://httpd.apache.org/
5/usr/local/Cellar/httpd/2.4.58 (1,663 files, 31.8MB) *
6 Poured from bottle using the formulae.brew.sh API on 2023-11-09 at 18:19:19
7From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/h/httpd.rb
8License: Apache-2.0
9==> Dependencies
10Required: apr ✔, apr-util ✔, brotli ✔, libnghttp2 ✔, openssl@3 ✔, pcre2 ✔
11==> Caveats
12DocumentRoot is /usr/local/var/www
In the file, add the following content:
1<?php
2echo("Hello World");
3?>
Next, let's talk about how to run a PHP program in localhost. Navigate to http://localhost:8080/info.php and you should see a blank page with just the Hello World text.
Next, edit the info.php file content to:
1<?php
2phpinfo();
3?>
Save, and then refresh the info.php page. You should see a page with a large table of PHP information like this:
phpinfo table
IMPORTANT: In production servers, it’s unsafe to expose information displayed by phpinfo() on a publicly accessible page
The information that we’re interested could be in these places:
  • “Configuration File (php.ini) Path” property shows where your PHP runtime is getting its php.ini file from. It can happen that the mongodb.so extension was added in the wrong php.ini file as there may be more than one.
  • “Additional .ini files parsed” shows potential extra PHP configuration files that may impact your specific configuration. These files are in the directory listed by the “Scan this dir for additional .ini files” section in the table.
There’s also a whole “mongodb” table that looks like this:
the MongoDB section in phpinfo
Its presence indicates that the MongoDB extension has been properly loaded and is functioning. You can also see its version number to make sure that’s the one you intended to use.
If you don’t see this section, it’s likely the MongoDB extension failed to load. If that’s the case, look for the “error_log” property in the table to see where the PHP error log file is, as it may contain crucial clues. Make sure that “log_errors” is set to ON. Both are located in the “Core” PHP section.
If you are upgrading to a newer version of PHP, or have multiple versions installed, keep in mind that each version needs to have its own MongoDB extension and php.ini files.

Start a MongoDB Cluster on Atlas

Now that you've got your local environment set up, it's time to create a MongoDB database to work with, and to load in some sample data you can explore and modify.
Get started with an M0 cluster on Atlas today. It's free forever, and it's the easiest way to try out the steps in this blog series.
It will take a couple of minutes for your cluster to be provisioned, so while you're waiting, you can move on to the next step.

Set Up Your MongoDB Instance

Hopefully, your MongoDB cluster should have finished starting up now and has probably been running for a few minutes.
The following instructions were correct at the time of writing but may change, as we're always improving the Atlas user interface:
In the Atlas web interface, you should see a green button at the bottom-left of the screen, saying "Get Started." If you click on it, it'll bring up a checklist of steps for getting your database set up. Click on each of the items in the list (including the "Load Sample Data" item—we'll use this later to test the PHP library), and it'll help you through the steps to get set up.
The fastest way to get access to data is to load the sample datasets into your cluster right in the Atlas console. If you're brand new, the new user wizard will actually walk you through the process and prompt you to load these.
If you already created your cluster and want to go back to load the sample datasets, click the ellipsis (three dots) next to your cluster connection buttons (see below image) and then select Load Sample Dataset.
Load Sample Dataset
Now, let's move on to setting the configuration necessary to access your data in the MongoDB Cluster. You will need to create a database user and configure your IP Address Access List.

Create a User

Following the "Get Started" steps, create a user with "Read and write access to any database." You can give it the username and password of your choice. Make a copy of them, because you'll need them in a minute. Use the "autogenerate secure password" button to ensure you have a long, random password which is also safe to paste into your connection string later.

Add Your IP Address to the Access List

When deploying an app with sensitive data, you should only whitelist the IP address of the servers which need to connect to your database. To whitelist the IP address of your development machine, select "Network Access," click the "Add IP Address" button, and then click "Add Current IP Address" and hit "Confirm."

Connect to Your Database

The last step of the "Get Started" checklist is "Connect to your Cluster." Select "Connect your application" and select "PHP" with a version of "PHPLIB 1.8."
Connect via PHP
Click the "Copy" button to copy the URL to your paste buffer. Save it to the same place you stored your username and password. Note that the URL has <password> as a placeholder for your password. You should paste your password in here, replacing the whole placeholder, including the < and > characters.
Now it's time to actually write some PHP code to connect to your MongoDB database! Up until now, we've only installed the supporting system components. Before we begin to connect to our database and use PHP to manipulate data, we need to install the MongoDB PHP Library.
Composer is the recommended installation tool for the MongoDB library. Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
To install composer, we can use Homebrew.
1brew install composer

Installing the MongoDB PHP Library

Once you have composer installed, you can move forward to installing the MongoDB Library.
Installation of the library should take place in the root directory of your project. Composer is not a package manager in the same sense as Yum or Apt are. Composer installs packages in a directory inside your project. By default, it does not install anything globally.
1$ composer require mongodb/mongodb
2Using version ^1.8 for mongodb/mongodb
3./composer.json has been created
4Running composer update mongodb/mongodb
5Loading composer repositories with package information
6Updating dependencies
7Lock file operations: 4 installs, 0 updates, 0 removals
8- Locking composer/package-versions-deprecated (1.11.99.1)
9- Locking jean85/pretty-package-versions (1.6.0)
10- Locking mongodb/mongodb (1.8.0)
11- Locking symfony/polyfill-php80 (v1.22.0)
12Writing lock file
13Installing dependencies from lock file (including require-dev)
14Package operations: 4 installs, 0 updates, 0 removals
15- Installing composer/package-versions-deprecated (1.11.99.1): Extracting archive
16- Installing symfony/polyfill-php80 (v1.22.0): Extracting archive
17- Installing jean85/pretty-package-versions (1.6.0): Extracting archive
18- Installing mongodb/mongodb (1.8.0): Extracting archive
19Generating autoload files
20composer/package-versions-deprecated: Generating version class...
21composer/package-versions-deprecated: ...done generating version class
222 packages you are using are looking for funding.
Make sure you're in the same directory as you were when you used composer above to install the library.
In your code editor, create a PHP file in your project directory called quickstart.php. If you're referencing the example, enter in the following code:
1<?php
2
3 require_once __DIR__ . '/vendor/autoload.php';
4
5 $client = new MongoDB\Client(
6 'mongodb+srv://<username><password>@myfirstcluster.zbcul.mongodb.net/dbname?retryWrites=true&w=majority');
7
8 $customers = $client->selectCollection('sample_analytics', 'customers');
9 $document = $customers->findOne(['username' => 'wesley20']);
10
11 var_dump($document);
12
13?>
<username> and <password> are the username and password you created in Atlas, and the cluster address is specific to the cluster you launched in Atlas.
Save and close your quickstart.php program and run it from the command line:
1$ php quickstart.php
If all goes well, you should see something similar to the following:
1$ php quickstart.php
2object(MongoDB\Model\BSONDocument)#12 (1) {
3["storage":"ArrayObject":private]=>
4 array(8) {
5 ["_id"]=>
6 object(MongoDB\BSON\ObjectId)#16 (1) {
7 ["oid"]=>
8 string(24) "5ca4bbcea2dd94ee58162a72"
9 }
10 ["username"]=>
11 string(8) "wesley20"
12 ["name"]=>
13 string(13) "James Sanchez"
14 ["address"]=>
15 string(45) "8681 Karen Roads Apt. 096 Lowehaven, IA 19798"
16 ["birthdate"]=>
17 object(MongoDB\BSON\UTCDateTime)#15 (1) {
18 ["milliseconds"]=>
19 string(11) "95789846000"
20 }
21 ["email"]=>
22 string(24) "josephmacias@hotmail.com"
23 ["accounts"]=>
24 object(MongoDB\Model\BSONArray)#14 (1) {
25 ["storage":"ArrayObject":private]=>
26 array(1) {
27 [0]=>
28 int(987709)
29 }
30 }
31 ["tier_and_details"]=>
32 object(MongoDB\Model\BSONDocument)#13 (1) {
33 ["storage":"ArrayObject":private]=>
34 array(0) {
35 }
36 }
37 }
38}
You just connected your PHP program to MongoDB and queried a single document from the sample_analytics database in your cluster! If you don't see this data, then you may not have successfully loaded sample data into your cluster. You may want to go back a couple of steps until running this command shows the document above.

Securing Usernames and Passwords

Storing usernames and passwords in your code is never a good idea. So, let's take one more step to secure those a bit better. It's general practice to put these types of sensitive values into an environment file such as .env. The trick, then, will be to get your PHP code to read those values in. Fortunately, Vance Lucas came up with a great solution called phpdotenv. To begin using Vance's solution, let's leverage composer.
1$ composer require vlucas/phpdotenv
Now that we have the library installed, let's create our .env file which contains our sensitive values. Open your favorite editor and create a file called .env, placing the following values in it. Be sure to replace your user name and your password with the actual values you created when you added a database user in Atlas.
1MDB_USER="your user name"
2MDB_PASS="your password"
Next, we need to modify our quickstart.php program to pull in the values using phpdotenv. Let's add a call to the library and modify our quickstart program to look like the following. Notice the changes on lines 5, 6, and 9.
1<?php
2
3require_once __DIR__ . '/vendor/autoload.php';
4$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
5$dotenv->load();
6
7$client = new MongoDB\Client(
8 'mongodb+srv://'.$_ENV['MDB_USER'].':'.$_ENV['MDB_PASS'].'@tasktracker.zbcul.mongodb.net/sample_analytics?retryWrites=true&w=majority'
9);
10
11$customers = $client->selectCollection('sample_analytics', 'customers');
12$document = $customers->findOne(['username' => 'wesley20']);
13
14var_dump($document);
Next, to ensure that you're not publishing your credentials into git or whatever source code repository you're using, be certain to add a .gitignore (or equivalent) to prevent storing this file in your repo. Here's my .gitignore file:
1composer.phar
2/vendor/
3.env
My .gitignore includes files that are leveraged as part of our libraries—these should not be stored in our project.
Should you want to leverage my project files, please feel free to visit my github repository, clone, fork, and share your feedback in the Community.
This quick start was intended to get you set up to use PHP with MongoDB. You should now be ready to move onto the next article in this series. Please feel free to contact me in the Community should you have any questions about this article, or anything related to MongoDB.
Please be sure to visit, star, fork, and clone the companion repository for this article.

References


Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Code Example

Introducing the Tour Planner With MongoDB Vector Search


Sep 24, 2024 | 5 min read
Tutorial

How To Build a Laravel + MongoDB Back End Service


Oct 01, 2024 | 15 min read
News & Announcements

MongoDB PHP Extension 1.13.0 Released


May 24, 2022 | 1 min read
Podcast

Exploring the PHP Driver With Jeremy Mikola - Podcast Episode


Aug 28, 2024 | 29 min
Table of Contents