@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 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; } ?> |
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.