> This page location: /docs.md > /docs/drivers.md > /docs/languages/php.md > /docs/php-library/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: create-file-mac-linux, create-file-windows, shell, dotenv
-->

# Get Started with the MongoDB PHP Library

## Overview

The MongoDB PHP Library is a high-level abstraction for the MongoDB PHP extension, which you can use to connect to MongoDB and interact with data stored in your deployment. This guide shows you how to create an application that uses the MongoDB PHP Library to connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster.

**Tip:**

MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.

Follow this guide to connect a sample PHP application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our [list of official drivers.](https://www.mongodb.com/docs/drivers/)

## Download and Install

1. Install dependencies.

   Before you begin developing, ensure that you have the following dependencies installed on your local machine:

   - [PHP](https://php.net/install) version 7.4 or later

   - [Composer](https://getcomposer.org/download/) version 2.0 or later

   - [pie](https://github.com/php/pie)

2. Install the MongoDB PHP extension.

   Run the following command to install the `mongodb` PHP extension:

   ```bash
   pie install mongodb/mongodb-extension
   ```

   **Tip: Specify the PHP Extension Version**

   To install a specific version of the PHP extension, include the version number as shown in the following command:

   ```bash
   pie install mongodb/mongodb-extension:^2.5.0
   ```

   To install a PHP extension version before v1.21, you must use the [pecl command.](https://php.net/mongodb.installation#mongodb.installation.pecl)

3. Create a project directory.

   From your root directory, run the following command in your shell to create a directory called `php-quickstart` for this project:

   ```bash
   mkdir php-quickstart
   ```

   Select the tab corresponding to your operating system and run the following commands to create a `quickstart.php` application file in the `php-quickstart` directory:

   ### macOS / Linux

   ```bash
   cd php-quickstart
   touch quickstart.php
   ```

4. Install the MongoDB PHP Library.

   To install the MongoDB PHP Library, run the following command in your `php-quickstart` directory:

   ```bash
   composer require mongodb/mongodb
   ```

   After installing the library, include Composer's `autoload.php` file by adding the following code to the top of your `quickstart.php` file:

   ```php
   <?php

   require_once __DIR__ . '/vendor/autoload.php';
   ```

After you complete these steps, you have a new project directory, a new application file, and the library dependencies installed.

## Create a MongoDB Deployment

You can create a free cluster on MongoDB Atlas to store and manage your data. MongoDB Atlas hosts and manages your MongoDB database in the cloud.

1. Create a free MongoDB deployment on Atlas.

   Complete the [MongoDB Get Started](https://www.mongodb.com/docs/get-started.md#std-label-unified-get-started) guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment. Follow the instructions in the Cloud Deployment tabs to create your MongoDB Atlas deployment in the cloud.

2. Save your credentials.

   After you create your database user, save that user's database username and database password to a safe location for use in an upcoming step.

After you complete these steps, you have a new free cluster on Atlas, database user credentials, and sample data loaded into your database.

## Create a Connection String

You can connect to your MongoDB deployment by providing a **connection URI**, also called a *connection string*, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.

The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.

To connect to an instance or deployment not hosted on Atlas, see [Choose a Connection Target.](https://www.mongodb.com/docs/php-library/current/connect/connection-targets.md#std-label-php-connection-targets)

1. Find your MongoDB Atlas connection string.

   To retrieve your connection string for the deployment that you created in the [previous step](https://www.mongodb.com/docs/php-library/current/get-started.md#std-label-php-create-deployment), log in to your Atlas account and navigate to the Clusters page under the Database section. Click the Connect button for your new deployment.

   ![The connect button in the clusters section of the Atlas UI](/_includes/figures/atlas_connect_to_cluster.png)

   If you do not already have a database user configured, MongoDB will prompt you to create and configure a new user.

   Click the Drivers button under Connect to your application section and select "PHP" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.

   Ensure the View full code sample option is deselected to view only the connection string.

2. Copy your connection string.

   Click the button on the right of the connection string to copy it to your clipboard, as shown in the following screenshot:

   ![The copy button next to the connection string in the Atlas UI](/_includes/figures/atlas_copy_connection_string_php.png)

3. Update the password placeholders.

   Paste this connection string into a file in your preferred text editor and replace the `<db_password>` placeholder with your database user's password. The connection string is already populated with your database user's username.

   Save this file to a safe location for use in the next step.

After completing these steps, you have a connection string that corresponds to your Atlas cluster.

## Run a Sample Query

After retrieving the connection string for your MongoDB Atlas deployment, you can connect to the deployment from your PHP application and query the Atlas sample datasets.

1. Edit your PHP application file.

   Copy and paste the following code into the `quickstart.php` file, which queries the `movies` collection in the `sample_mflix` database:

   ```php
   <?php

   require __DIR__ . '/../vendor/autoload.php';


   $uri = getenv('MONGODB_URI') ?: throw new RuntimeException(
       'Set the MONGODB_URI environment variable to your Atlas URI',
   );
   $client = new MongoDB\Client($uri);
   $collection = $client->sample_mflix->movies;

   $filter = ['title' => 'The Shawshank Redemption'];
   $result = $collection->findOne($filter);

   if ($result) {
       echo json_encode($result, JSON_PRETTY_PRINT);
   } else {
       echo 'Document not found';
   }

   ```

2. Assign the connection string.

   Assign the `MONGODB_URI` environment variable to the connection string that you copied from the [Create a Connection String](https://www.mongodb.com/docs/php-library/current/get-started.md#std-label-php-connection-string) step of this guide. You can assign this variable by running a shell command or creating a `.env` file in your application, as show in the following tabs:

   ### Shell Command

   ```sh
   export MONGODB_URI=<connection string>
   ```

3. Run your PHP application.

   In your project directory, run the following shell command to start the application:

   ```bash
   php quickstart.php
   ```

   The command line output contains details about the retrieved movie document:

   ```none
   {
       "_id": {
           "$oid": "..."
       },
       ...
      "rated": "R",
      "metacritic": 80,
      "title": "The Shawshank Redemption",
      ...
   }
   ```

   If you encounter an error or see no output, ensure that you assigned the proper connection string to the `MONGODB_URI` environment variable and that you loaded the sample data.

After you complete these steps, you have a PHP application that connects to your MongoDB deployment, runs a query on the sample data, and returns a matching document.

## Next Steps

Congratulations on completing the quick start tutorial!

**Note:**

If you run into issues on this step, submit feedback by using the Rate this page tab on the right or bottom right side of this page.

You can find support for general questions by using the MongoDB [Stack Overflow tag](https://stackoverflow.com/questions/tagged/mongodb) or the MongoDB [Reddit community.](https://www.reddit.com/r/mongodb/)

In this tutorial, you created a PHP application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.

Learn more about the MongoDB PHP Library from the following resources:

- Learn how to configure your MongoDB connection in the [Connect to MongoDB](https://www.mongodb.com/docs/php-library/current/connect.md#std-label-php-connect) section.

- Learn how to perform read and write operations in the [CRUD Operations](https://www.mongodb.com/docs/php-library/current/crud/insert.md#std-label-php-write-insert) section.

## Troubleshooting

This section addresses issues that you might encounter when installing the PHP library and its dependencies.

### PHP Headers Not Found

You might see a header file error that resembles the following code when installing the PHP library:

```none
/private/tmp/pear/install/mongodb/php_phongo.c:24:10: fatal error: 'php.h' file not found

#include <php.h>
         ^~~~~~~
```

This error indicates that PHP's build system cannot find the necessary headers. All PHP extensions require headers to compile. Those headers must correspond to the PHP runtime for which the extension will be used. The `phpize` command, which is invoked by `pecl` and `pie`, usually ensures that the extension builds with the correct headers.

If you install a PHP runtime, the corresponding headers are not always automatically available. On many Linux distributions, headers are often published under a separate `php-dev` or `php-devel` package. On macOS, the default PHP runtime does not include headers. Users typically must install PHP and its headers by using [Homebrew.](https://brew.sh/)

### Multiple PHP Runtimes Installed

If your system has multiple versions of PHP installed, each version will have its own `pecl`, `pie`, and `phpize` commands. Additionally, each PHP runtime may have separate `php.ini` files for each server application programming interface (SAPI), such as FPM and CLI. If you installed the extension but it is not available at runtime, ensure that you use the correct `pecl` or `pie` command and modify the appropriate `php.ini` file.

To see which `php.ini` file a PHP runtime uses, view the output of [phpinfo()](https://php.net/phpinfo) for that particular SAPI. Additionally, you can use [php\_ini\_loaded\_file()](https://php.net/php_ini_loaded_file) and [php\_ini\_scanned\_files()](https://php.net/php_ini_scanned_files) to determine which INI files have been loaded by PHP.

To debug issues when the extension is not loaded, you can use the `detect-extension` script provided in the tools directory. You can run this script from the CLI or include it in a script available to your web server. The tool finds potential issues and installation instructions for your system. If you installed the library by using Composer, you can call the script from the vendor directory as shown in the following code:

```none
php vendor/mongodb/mongodb/tools/detect-extension.php
```

If you want to check configuration for a web server SAPI, include the file in a script available to the web server and open it in your browser. Ensure that you wrap the script in `<pre>` tags to properly format its output as shown in the following code:

```php
<pre><?php require(...); ?></pre>
```

### Loading an Incompatible DLL on Windows

Windows binaries are available for several combinations of a PHP version, thread safety setting (TS or NTS), and architecture type (x86 or x64). Failure to select the correct binary causes an error when attempting to load the extension DLL at runtime, as shown in the following sample output:

```none
PHP Warning:  PHP Startup: Unable to load dynamic library 'mongodb'
```

Ensure that you have downloaded a DLL that corresponds to the following PHP runtime properties:

- PHP version (`PHP_VERSION`)

- Thread safety (`PHP_ZTS`)

- Architecture (`PHP_INT_SIZE`)

In addition to the preceding constants, these properties can also be inferred from [phpinfo()](https://php.net/phpinfo). If your system has multiple PHP runtimes installed, view the `phpinfo()` output for the correct environment.

You can also use the `detect-extension` script described in the previous section to determine the correct DLL for your PHP environment.
