Export Database & Zip it using PHP shell_exec()

I create a quick route that triggering an fn that runs shell_exec() to back up my database.

mysqldump -u john -p123 db1 > /home/john/db1.04-20-21-11-28-am.sql

To save server space, I also want to zip what I dumped

tar -czvf db1.04-20-21-11-28-am.sql.tar.gz db1.04-20-21-11-28-am.sql && rm -rf db1.04-20-21-11-28-am.sql

I’m not sure why the zip command never runs even if I put a sleep() after the first one, and in betweens.

What did I do wrong?

Note : the tar command working perfectly if I copy and run it on the command line in the server.


Code

public function dbBackUp()
{

    $un = env('DB_USERNAME');
    $pw = env('DB_PASSWORD');
    $db = env('DB_DATABASE');

    $date = date('m-d-y-g-i-a');

    $cmd = 'mysqldump -u ' . $un . ' -p' . $pw . ' ' . $db . ' > /home/john/' . $db . '.'.$date.'.sql';
    $result = shell_exec($cmd);

    sleep(2);

    $cmd2 = 'tar -czvf '. $db . '.'. $date .'.sql.tar.gz '. $db .'.'.$date.'.sql && rm -rf '. $db .'.'.$date.'.sql';
    $result2 = shell_exec($cmd2);
    
    $un = env('DB_USERNAME');
    $pw = env('DB_PASSWORD');
    $db = env('DB_DATABASE_BABIES');
    $cmd3 = 'mysqldump -u ' . $un . ' -p' . $pw . ' ' . $db . ' > /home/john/' . $db . '.'.$date.'.sql';
    $result3 = shell_exec($cmd3);

    sleep(2);

    $cmd4 = 'tar -czvf '. $db . '.'. $date .'.sql.tar.gz '. $db .'.'.$date.'.sql && rm -rf '. $db .'.'.$date.'.sql';
    $result4 = shell_exec($cmd4);
    sleep(2);

    $data = []; 

    if($result != null ){
        return View::make('layouts.dbBackUp');
    } else {
        return $data;
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think you’re missing “/home/john/” part from the tar command so it wont find the file.

Maybe this will help:

//change to the directory that contains the file you want to zip
chdir('/home/john/');

$cmd2 = 'tar -czvf '. $db . '.'. $date .'.sql.tar.gz '. $db .'.'.$date.'.sql && rm -rf '. $db .'.'.$date.'.sql';
$result2 = shell_exec($cmd2);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x