I am working on a function for a PostgreSQL database, that when client issues a database dump, the dump is offered as a download. This snapshot could then later be used to restore the database with. However, I can’t seem to figure out how to do it. When the user presses the button, an AJAX call to the server is made, as to which the server executes the following code:
if($_POST['command'] == 'dump'){
$dump = $table->Dump();
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename=/"'.$dump.'/"');
}
Where $table->Dump() looks like this:
public function Dump(){
$filename = dirname(__FILE__)."/db_Dump.out";
exec("pg_dump ".$this->name." > $filename");
return $filename;
}
The dump isn’t made though. Any tips on this?
This approach however, doesn’t work. I thought that setting the headers would be enough to cause a download, but apparently I was wrong. So what would be the correct way of creating a download?
Edit 1, @stevevls:
if($_POST['command'] == 'dump'){
$dump = $table->Dump();
$fh = fopen($dump, 'r') or die("Can't open file");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename=/"'.$dump.'/"');
$dumpData = fread($fh, filesize($fh));
fclose($fh);
echo $dumpData;
}
I still don’t get anything as a download though.
Edit 2, @myself
I have been able to get a return value, it seemed that the the check if the command given was ‘dump’ was never reached. I fixed that, and now I get an error on the pg_dump command. I now get
sh: cannot create ../database/db_Dump.sql: Permission denied
I bet this is due to php not being allowed to run pg_dump, but how could I get the system to allow it to be able to run it?
Edit 3, @myself
After resolving the issue with the pg__dump (I added www-data, Apaches user on my system, to the sudoers list, which resoved the issue. Also setting the correct permissions on the directory to write to is handy aswell.) I now get the db_Dump.sql as plain text instead of a save as dialog. Any ideas on that?
Turns out, it was all due to the fact of how I requested the download. It seems that it is impossible to get a download when you request it via Ajax, as the returned file get’s accepted in the success method of the call. After Changing this to a direct link to the file, I was able to get a download.