Current Location: Home> Latest Articles> Complete Guide to Configuring PHP and MongoDB on CentOS

Complete Guide to Configuring PHP and MongoDB on CentOS

gitbox 2025-06-14

With the advancement of modern application development, the combination of PHP and MongoDB has become increasingly popular among developers. This article will guide you through the process of successfully configuring PHP and MongoDB on a CentOS system to help you get started with your development project quickly.

1. Preparation

Before you start, make sure your CentOS system is updated and that PHP is already installed. You can check the current PHP version with the following command:

php -v

If PHP is not installed, you can install it by running the following command:

sudo yum install php php-cli php-pear

2. Install MongoDB

Next, you need to configure the MongoDB repository. Use the following command to add the MongoDB YUM repository:

cat <<EOF > /etc/yum.repos.d/mongodb-org-4.4.repo
[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc
EOF

Then, use the following command to install MongoDB:

sudo yum install -y mongodb-org

3. Start the MongoDB Service

Once MongoDB is installed, start the MongoDB service using the following command:

sudo systemctl start mongod

To ensure that MongoDB starts automatically when the system reboots, run the following command:

sudo systemctl enable mongod

4. Install the MongoDB PHP Extension

In order for PHP to interact with MongoDB, you need to install the MongoDB PHP extension. Run the following command to install it:

sudo pecl install mongodb

Once the installation is complete, add the following line to your PHP configuration file:

echo "extension=mongodb.so" | sudo tee /etc/php.d/45-mongodb.ini

5. Verify the Installation

After restarting the PHP service, you can verify that the MongoDB PHP extension has been successfully loaded by running the following command:

php -m | grep mongodb

If you see "mongodb" in the output, congratulations! You've successfully configured PHP with MongoDB.

Summary

With this guide, you have successfully configured PHP and MongoDB on your CentOS system. This setup provides robust support for your development projects, allowing you to leverage the strengths of both technologies. If you encounter any issues, feel free to refer to the official documentation or seek help from the developer community.