Do a MySQL backup from a PHP script

  • January 21, 2008
  • Avatar for peter
    Peter
    Upfold

In today's FOSSwire programming special, I'm going to be showing you how to build a script in PHP that will allow you to back up your MySQL database remotely, using just a web browser.

Why might you need such a script? Well, remote backup through a web browser could be very useful, as you will be able to do it from any machine with a web browser, where you might not have the ability to or want to log in via SSH.

First of all, I need to point out an important point. This example will have no authentication in it. That means anyone that can find this script can perform a backup of your MySQL databases should they know a valid password, or could try knocking at the door to see if they can get in. I strongly advise you restrict access to the script we're about to write using some form of authentication, be it through .htpasswd or similar, or by building a custom login system on top of this.

A few more notes:

  • This script is basic. It's not designed to be super-duper, and it's probably best as a starting point for your own script. Take it with a pinch of salt.
  • It needs a directory writable to the web server to store its files. This should most definitely be outside of the web root - i.e. impossible for anyone to download your raw database dumps in their browser.
  • Any errors that happen in the mysqldump process will get thrown right back onto the browser. Making that cleaner and better is outside the scope of this script.
  • It's ugly, but making it pretty isn't my job, or my expertise. ;)
  • It is designed for servers where MySQL runs on localhost (i.e. the same box as the web server). It can be easily adapted though, just by changing the mysqldump command string.
  • The mysqldump program must be in the PATH, or else you must supply the full path to it in $command.

And that is it. Properly in place, that script is a very simple, down and dirty interface to remotely back up your MySQL databases from a web browser.

Avatar for peter Peter Upfold

Home » Articles »