MongoDB with Php crud operation[session]

1️⃣ Check Your PHP Environment

Open a command prompt and run:

php -v

Note the PHP version, architecture (x64 or x86), and whether it’s Thread Safe (TS) or Non-Thread Safe (NTS).


2️⃣ Download the Correct Extension DLL

  1. Go to the official PECL page:
    https://pecl.php.net/package/mongodb
  2. Choose the latest stable release (e.g. mongodb-1.x.x).
  3. Download the zip matching:
    • Your PHP version (e.g. 8.2, 8.1, 7.4…)
    • Your architecture (x64 or x86)
    • TS or NTS as reported by php -v.

Inside the zip you’ll find php_mongodb.dll.


3️⃣ Install the Extension

  • Copy php_mongodb.dll into: C:\xampp\php\ext

4️⃣ Enable in php.ini

  1. Open: C:\xampp\php\php.ini
  2. Add (or uncomment) this line: extension=mongodb
  3. Save the file.

5️⃣ Restart Apache

Use the XAMPP Control Panel:

  • Stop Apache
  • Start Apache again

6️⃣ Verify Installation

Create a file info.php in htdocs:

<?php phpinfo();

Open http://localhost/info.php and search for mongodb.
You should see something like:

MongoDB support => enabled

If you don’t see it, re-check that the DLL matches your PHP version and that you edited the correct php.ini (XAMPP has both php\php.ini and apache\bin\php.ini—edit the one used by Apache, usually C:\xampp\php\php.ini).


7️⃣ Use the New Driver in Code

After the extension loads, use Composer’s library in your PHP code:

composer require mongodb/mongodb

Then in register.php:

require 'vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$db     = $client->selectDatabase('yourdb');

Important:
Do not use the legacy MongoClient or new Mongo() syntax.
The current driver works with MongoDB\Client (from Composer) or MongoDB\Driver\Manager (low-level).


1️⃣ register.php (with session start)

This script registers the user and starts a session so you can store the username.

<?php
session_start();  // Start or resume the session

if (isset($_POST['submit'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if ($username === '' || $password === '') {
        exit("Username and password required.");
    }

    try {
        $m = new MongoDB\Driver\Manager('mongodb://localhost:27017');
    } catch (MongoDB\Driver\Exception\Exception $e) {
        exit("MongoDB connection failed: " . $e->getMessage());
    }

    // Optional: create collection if not exists
    $command = new MongoDB\Driver\Command(["create" => 'e1']);
    try {
        $m->executeCommand("login", $command);
    } catch (MongoDB\Driver\Exception\CommandException $e) {
        if ($e->getCode() != 48) { // 48 = namespace exists
            exit("Error creating collection: " . $e->getMessage());
        }
    }

    // Insert new user
    $bulk = new MongoDB\Driver\BulkWrite;
    $bulk->insert([
        "username" => $username,
        "password" => password_hash($password, PASSWORD_BCRYPT)
    ]);

    try {
        $m->executeBulkWrite('login.e1', $bulk);

        // Store username in session
        $_SESSION['username'] = $username;

        header('Location: page2.php');
        exit;
    } catch (MongoDB\Driver\Exception\BulkWriteException $e) {
        exit("Error inserting document: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html>
<body>
<center><h1>Registration Form</h1></center>
<form action="" method="post">
    <label>Username :</label>
    <input type="text" name="username"><br>
    <label>Password :</label>
    <input type="password" name="password"><br><br>
    <input type="submit" value="Register" name="submit">
</form>
</body>
</html>

2️⃣ page2.php (protected page)

<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header('Location: register.php'); // or a login page
    exit;
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</h1>
<p>This is a protected page.</p>
<a href="logout.php">Logout</a>
</body>
</html>

3️⃣ logout.php (destroy session)

<?php
session_start();
session_unset();   // remove all session variables
session_destroy(); // destroy the session
header('Location: register.php');
exit;

How It Works

  • session_start() must be the first line (before any output) on every page that uses sessions.
  • After successful registration, we store $_SESSION['username'].
  • Any protected page checks isset($_SESSION['username']).
  • Logging out simply calls session_destroy().

With these changes, your MongoDB-based registration now supports full PHP session management.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *