How to backup MongoDB data using PHP?

Member

by shyann , in category: PHP Databases , a year ago

How to backup MongoDB data using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a year ago

@shyann 

To backup MongoDB data using PHP, you can use the mongodump command-line utility to create a backup of your database. Here are the steps to do it:

  1. Install the MongoDB PHP driver on your server if you haven't done so already.
  2. Create a PHP script that uses the exec() function to execute the mongodump command-line utility. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
// Set the path to the mongodump utility
$dumpPath = '/usr/bin/mongodump';

// Set the MongoDB connection information
$host = 'localhost';
$port = '27017';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';

// Set the backup directory and filename
$backupDir = '/path/to/backup/directory';
$backupFile = $database . '-' . date('Y-m-d-H-i-s') . '.tar.gz';

// Construct the command to execute
$command = sprintf(
    '%s --host %s --port %s --username %s --password %s --db %s --archive=%s/%s --gzip',
    $dumpPath,
    $host,
    $port,
    $username,
    $password,
    $database,
    $backupDir,
    $backupFile
);

// Execute the command
exec($command, $output, $returnVar);

// Check the return value for errors
if ($returnVar !== 0) {
    echo "Error: Failed to create backup";
} else {
    echo "Backup created successfully: " . $backupFile;
}
?>


  1. Save the PHP script to your server and execute it. The script will create a backup of your MongoDB database and save it to the specified backup directory.


Note: You should replace the placeholders with your own MongoDB connection information and backup directory path. Also, make sure that the user running the PHP script has permission to execute the mongodump command and write to the backup directory.