1

To backup MySQL database via PHP command, I found this code:

<?php

$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";

$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";

header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );

$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";   

passthru( $cmd );

exit(0);
?>

The code works great when saved into a .PHP file and the page is loaded. It automatically downloads the .sql.gz file to the browser's downloads folder, no user intervention required. However, I need to execute only when user presses a button - therefore, via AJAX.

However, when I call the code via AJAX, nothing happens. If I alert the output of the AJAX command, I get the binary file contents.

So, how do I make the AJAX output save into browser's downloads folder?

Here's my jQuery code to call the backup.php file:

$('#btnBackupNow').click(function(){
    $.ajax({
        type: 'post',
         url: 'ajax/dobackup.php',
        success: function(d){
                //alert(d); //<=== displays binary data (gzipped)
                //$('#btnBackupNow').fadeOut();
        }
    });
});

PS - If you like the backup code, please visit the original question and upvote the answer I got it from.


SOLUTION:

Do not use AJAX at all.

Save the above code, as is (with correct passwords etc), in a separate PHP file, such as do_db_backup.php.

Have a hidden iFrame on the page:

<iframe id="iBkup" style="display:none;"></iframe>

Upon button click, set the src= attribute of the iFrame to the PHP file that has the backup code:

$('#btnBackupNow').click(function(){
    $('#iBkup').attr('src','do_db_backup.php');
});

Click the button and watch the magic happen.

Community
  • 1
  • 1
crashwap
  • 2,846
  • 3
  • 28
  • 62

0 Answers0