I am coding a php script for backup a database, the idea is to use mysqldump command and then download a sql file with the result, unfortunately the output of the mysqldump is not save on the file, just the source code. This is the code:
$archivo = 'bkbiblioteca_' . date("d-m-Y_H:i:s") . '.sql';
$comando = "mysqldump --add-drop-table --host=$servidor --user=$usuario --password=$clave $base > $archivo";
try{
$archivo_manejador = fopen($archivo, 'w+');
fwrite($archivo_manejador, $comando);
fclose($archivo_manejador);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($archivo));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($archivo));
ob_clean();
flush();
readfile($archivo);
unlink($archivo);
}catch(\Exception $e){
echo 'error en el proceso de bk' . $e->getMessage(); //TODO: favor incluir en la bitacora global del sistema
}//fin de catch
Right now I am getting the file with this line: mysqldump --add-drop-table --host=$servidor --user=$usuario --password=$clave $base > $archivo
I have tried with this command:
system("$comando");
But it does not work, so I can't not figure out how to execute the mysqldump command and obtain the result in the file instead of get the source code line.
Thanks in advance
Use the --result-file
option of mysqldump
to create the dump file which you may then send to the browser for download. The full command would be (insert your file names as desired):
exec('mysqldump --user=backup --password="yourpasswordhere#" --routines --insert-ignore --complete-insert --force --result-file=name_of_your_dump_file_here.sql --databases ' . $yourdatabasename);