Software Development Engineer

Blog PostsResume

Store and Retrieve Images From MongoDB Using PHP

While I was working on my project prelimQuiz, I got stuck at a serious problem. In a quiz, the quizmaster might need to add images along with the question, I had to add this feature, and for that, the uploaded image has to be stored and retrieved from the database. Since it was the first time I was integrating MongoDB with PHP, so I had no command over the predefined helper functions. Adding to my problem was the fact that the extension of MongoDB driver for PHP is now deprecated, and most of the tutorials online were for this legacy driver. After researching for quite some time, I found the solution.

In my project, this feature is implemented in an Object Oriented format. So, I'll try to make it as easy to understand as possible for me. The following pieces of code may have some reminiscences of the projects.

PREREQUISITES:

Code Snapshots

Uploading Image

<form method="POST" action="" enctype="multipart/form-data">
  ...................
  <input type="file" name="cover" >
  ..................
  <button type="submit">Submit</button>
</form>

Retrieving image from $_FILE and storing it in a database collection

if (isset($_FILES["cover"])) {
  $questionCover = $_FILES["question_cover"];
  
  // Establish MongoDB Connection
  $connection = new MongoDB\Client("mongodb://localhost:27017");
  $databaseMongo = $connection->selectDatabase(Config::get('DB_NAME'));

  $questions = $databaseMongo->selectCollection("questions");
  $document = array(
      "type" => "MCQ",
      "cover" => new MongoDB\BSON\Binary(file_get_contents($questionCover["tmp_name"]), MongoDB\BSON\Binary::TYPE_GENERIC),
  );
  if ($questions->insertOne($document)) {
      return true;
  }
  return false;

Retrieve image from database

// Establish MongoDB Connection
$connection = new MongoDB\Client("mongodb://localhost:27017");
$databaseMongo = $connection->selectDatabase(Config::get('DB_NAME'));

$questions = $databaseMongo->selectCollection("questions");

$questionsArray = $questions->find()->toArray();

foreach ($questionsArray as $question) {
        if ($level == 1) {
            $myQuestion = $question;
            break;
        }
 }

Displaying image (as HTML image tag)

<img src="data:jpeg;base64,<?=base64_encode($myQuestion->cover->getData())?> " />

Displaying image (Alternative)

header('Content-Type: image/png');
imagepng(imagecreatefromstring($myQuestion->cover->getData()));

You can see the code in action @prelimQuiz


© 2024 Ujjwal Bhardwaj. All Rights Reserved.