Search code examples
phpmysqlexecexit-code

With this code will PHP wait before continuing?


I am creating a mysqldump with php and then would like the file to be downloaded and ultimately deleted after such.

My concern is that PHP will not wait for system($command); to complete before readfile($backup_file); and that unlink($backup_file); will delete before everything has been completed especially for very large databases.

I understand that PHP is single threaded and that system($command) will issue an exit code, but does that exit code simply mean PHP has passed the command to be processed or does that mean PHP will wait until MYSQL is complete?

Here is the code:

$backup_file = $backupDir.$devDB."-".date("Y-m-d-H-i").'.gz';
$command = "mysqldump --opt -h $DbHost -u$DbUser -p$DbPassword $devDB | gzip > $backup_file";
system($command);

if (file_exists($backup_file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($backup_file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backup_file));

    readfile($backup_file);
    unlink($backup_file);
    exit;

Solution

  • It's very possible you'll hit a timeout if you're executing this on a web server, but PHP is synchronous so it will not ever reach readfile() prior to system() returning.

    Since you have not sent anything to the background with your command, there is nothing that will cause system() to return prior to the command being executed. The real concern is you have no error checking beyond checking if the file exists, so you should be reviewing the exit code to make sure the mysqldump and gzip succeeded.

    I would also make sure you consider the security implications of using a password as a command line argument in shared servers.