Php script to automatically backup your mysql database

Here you can share scripts and discuss how to build and design websites.

Php script to automatically backup your mysql database

Postby Daniel on Sat Feb 09, 2008 6:18 pm

To install: (for automatic backup you will need cron) You will have this if you have got cpanel

1. Copy the text below into your text editor e.g notepad and save it as a .php file

Code: Select all
<?php

$dbhost        = 'localhost';  // hostname usually localhost
  $dbuser        = 'username';      // username for MySQL database
  $dbpass        = 'password';    // Password for MySQL database
  $dbname        = 'database';      // MySQL Database Name

  $use_gzip      = 'yes';        // Change to 'no' if you don't want files gzipped

  $remove_file   = 'no';        // Change to 'yes' if you want to delete the backup file from your account after sending. Pick yes to save server space

  $use_email     = 'yes';          // Change to 'yes' if you want the backup to be sent through email. If you pick yes, fill out the next 3 lines
  $send_to       = 'youre-mail';   // email address for backup file
  $send_from     = 'youre-mail'; // email address sending the email, doesn't matter can be same as above
  $subject       = "MySQL Database ($dbname) Backup - " . date("j F Y"); // this is the subject of the email being sent to you

  $use_ftp       = 'no'; // Change to 'yes' if you want the backup file uploaded to a remote FTP server? If you pick yes, you must fill out the next 4 lines
  $ftp_server    = 'ftp.yourdomain.co.uk';   // FTP address
  $ftp_user_name = 'username';   // FTP username
  $ftp_user_pass = 'password';   // FTP password
  $ftp_path      = "/backups";  // Path to upload on FTP server

  $echo_status = 'yes';   // Change to 'no' if you want the script to work silently (nothing will be sent to the screen)


# You probably don't need to edit below this line....
#-------------------------------------------------------------------------------

  $db = mysql_connect("$dbhost","$dbuser","$dbpass");
    mysql_select_db("$dbname",$db);

  $path = make_dir();
   
  if ($echo_status == 'yes') {
    print "<html><head><title>MySQL Database Backup</title></head><body>";
    print "<font face=Verdana size=2><h3>Starting Process...</h3><p>";
    print "Backup dumpfile in progress<ul>";
  }

  $result = mysql_query("show tables from $dbname");
  while (list($table) = mysql_fetch_row($result)) {
    $newfile .= get_def($table);
    $newfile .= "\n\n";
    $newfile .= get_content($table);
    $newfile .= "\n\n";
    $i++;
    if ($echo_status == 'yes') {
      print "<li>Dumped table $table</li>";
    }
  }

    $file_name = $dbname . "-" . date("Ymd-Hi") . ".sql";
    $file_path = $path . $file_name;

  if ($use_gzip == "yes") {
    $file_name .= ".gz";
    $file_path .= ".gz";
    $zp = gzopen($file_path, "wb9");
    gzwrite($zp,$newfile);
    gzclose($zp);

    if ($echo_status == 'yes') {
      print "</ul>Gzip-file is created...<br>";
    }
  } else {
    $fp = fopen($file_path, "w");
    fwrite($fp, $newfile);
    fclose($fp);

    if ($echo_status == 'yes') {
      print "<br>SQL-file is created...<br>";
    }
  }

  if ($use_email == 'yes') {
    $fileatt_type = filetype($file_path);
   
    $headers = "From: $send_from";
   
    // Read the file to be attached ('rb' = read binary)
    $fp = fopen($file_path,'rb');
    $data = fread($fp,filesize($file_path));
    fclose($fp);
   
    // Generate a boundary string
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
   
    // Add the headers for a file attachment
    $headers .= "\nMIME-Version: 1.0\n" ."Content-Type: multipart/mixed;\n" ." boundary=\"{$mime_boundary}\"";
   
    // Add a multipart boundary above the plain message
    $message = "This is a multi-part message in MIME format.\n\n" ."--{$mime_boundary}\n" ."Content-Type: text/plain; charset=\"iso-8859-1\"\n" ."Content-Transfer-Encoding: 7bit\n\n" .
    $message . "\n\n";
   
    // Base64 encode the file data
    $data = chunk_split(base64_encode($data));
   
    // Add file attachment to the message
    $message .= "--{$mime_boundary}\n" ."Content-Type: {$fileatt_type};\n" ." name=\"{$file_name}\"\n" ."Content-Disposition: attachment;\n" ." filename=\"{$file_name}\"\n" ."Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" ."--{$mime_boundary}--\n";
   
    // Send the message
    $ok = @mail($send_to, $subject, $message, $headers);
     
    if ($echo_status == 'yes') {
      print "<br>Mail is sent...<br>";
    }
  }
   
  if ($use_ftp == 'yes') {
    if ($use_gzip == 'yes') {
      $mode = FTP_BINARY;
    } else {
      $mode = FTP_ASCII;
    }
    $ftp_id       = ftp_connect($ftp_server);
    $login_result = ftp_login($ftp_id, $ftp_user_name, $ftp_user_pass);
    $upload       = ftp_put($ftp_id, $ftp_path . $file_name, $file_path, $mode);
    ftp_close($ftp_id);

    if ($echo_status == 'yes') {
      print "<br>Backup is uploaded to FTP server<br>";
    }
  }

  if ($remove_file == "yes") {
    unlink($file_name);
    if ($echo_status == 'yes') {
      print "<br>File is deleted...<br>";
    }
  }

  if ($echo_status == 'yes') {
    print "<br>Back up done!<p>";
    print "<br>� <a href=http://www.imbri.com>Imbri Web</a></font><p>";
    print "</body></html>";
  }


  function make_dir() {
    $page = split("/", getenv('SCRIPT_NAME'));
    $n = count($page)-1;
    $page = $page[$n];
    $page = split("\.", $page, 2);
    $extension = $page[1];
    $page = $page[0];
    $script     = "$page.$extension";
    $base_url     = "http://".$_SERVER['SERVER_NAME'];
    $directory     = $_SERVER['PHP_SELF'];
    $url_base = "$base_url$directory";
    $url_base = ereg_replace("$script", '', "$_SERVER[PATH_TRANSLATED]");

    $path = $url_base;

    return $path;
  }

  function get_def($table) {
    $def = "";
    $def .= "DROP TABLE IF EXISTS $table;\n";
    $def .= "CREATE TABLE $table (\n";
    $result = mysql_query("SHOW FIELDS FROM $table") or die("Table $table not existing in database");
    while($row = mysql_fetch_array($result)) {
      $def .= "    $row[Field] $row[Type]";
      if ($row["Default"] != "") $def .= " DEFAULT '$row[Default]'";
      if ($row["Null"] != "YES") $def .= " NOT NULL";
      if ($row[Extra] != "") $def .= " $row[Extra]";
      $def .= ",\n";
    }
    $def = ereg_replace(",\n$","", $def);
    $result = mysql_query("SHOW KEYS FROM $table");
    while($row = mysql_fetch_array($result)) {
      $kname=$row[Key_name];
      if(($kname != "PRIMARY") && ($row[Non_unique] == 0)) $kname="UNIQUE|$kname";
      if(!isset($index[$kname])) $index[$kname] = array();
      $index[$kname][] = $row[Column_name];
    }
    while(list($x, $columns) = @each($index)) {
      $def .= ",\n";
      if($x == "PRIMARY") $def .= "   PRIMARY KEY (" . implode($columns, ", ") . ")";
      else if (substr($x,0,6) == "UNIQUE") $def .= "   UNIQUE ".substr($x,7)." (" . implode($columns, ", ") . ")";
      else $def .= "   KEY $x (" . implode($columns, ", ") . ")";
    }
    $def .= "\n);";
    return (stripslashes($def));
  }

  function get_content($table) {
    $content="";
    $result = mysql_query("SELECT * FROM $table");
    while($row = mysql_fetch_row($result)) {
      $insert = "INSERT INTO $table VALUES (";
      for($j=0; $j<mysql_num_fields($result);$j++) {
        if(!isset($row[$j])) $insert .= "NULL,";
        else if($row[$j] != "") $insert .= "'".addslashes($row[$j])."',";
        else $insert .= "'',";
      }
      $insert = ereg_replace(",$","",$insert);
      $insert .= ");\n";
      $content .= $insert;
    }
    return $content;
  }

  /* Changelog
   
     Version 1.0 - August 15th, 2003

     Added HTML & cleaned up comments.

  */
?>


2. set the database username's and password to use with your website

3. upload to your webserver

4. Open cron on your webserver and in the commpand type the following (change the directory and file name)

php -q /directorytoyourfile/filename

Cpanel Users you will need to enter this php -q /home/yourusername/directory whereyourfileisstored/filename.php
-Daniel

Image
User avatar
Daniel
Site Admin
 
Posts: 474
Joined: Wed Dec 05, 2007 4:59 pm
Location: United Kingdom

Re: Php script to automatically backup your mysql database

Postby david2334 on Thu Feb 14, 2008 4:36 pm

thanks wanted somthing to automatically backup my database
User avatar
david2334
Registered Member
 
Posts: 3
Joined: Sat Dec 08, 2007 9:41 pm

Re: Php script to automatically backup your mysql database

Postby Blockis on Wed Feb 20, 2008 1:44 am

Can this be used for Forums?
User avatar
Blockis
Registered Member
 
Posts: 29
Joined: Wed Feb 20, 2008 1:22 am

Re: Php script to automatically backup your mysql database

Postby Daniel on Wed Feb 20, 2008 8:25 pm

Blockis wrote:Can this be used for Forums?


Yes i am currently using it on this forum i have been using it for a couple of weeks now as i still testing it has worked so far.
-Daniel

Image
User avatar
Daniel
Site Admin
 
Posts: 474
Joined: Wed Dec 05, 2007 4:59 pm
Location: United Kingdom

Re: Php script to automatically backup your mysql database

Postby sunils on Mon Feb 25, 2008 7:14 pm

I wanted a similar script for my site and forum. So thought of building one. But its time consuming. I just want to Confirm whether can it be used as link in the adminprofile page of my site.
User avatar
sunils
V.I.P
 
Posts: 57
Joined: Wed Feb 20, 2008 9:20 am

Re: Php script to automatically backup your mysql database

Postby Daniel on Mon Apr 21, 2008 8:42 pm

I am not sure about that i use it with cron jobs to execute it so i am not sure how you could execute it from a link.
-Daniel

Image
User avatar
Daniel
Site Admin
 
Posts: 474
Joined: Wed Dec 05, 2007 4:59 pm
Location: United Kingdom

Re: Php script to automatically backup your mysql database

Postby sunils on Wed Apr 23, 2008 5:41 pm

This is an important script which web designer can use to backup the database and later update their site if any error occurs.
User avatar
sunils
V.I.P
 
Posts: 57
Joined: Wed Feb 20, 2008 9:20 am

Re: Php script to automatically backup your mysql database

Postby aopsftw on Fri Jul 04, 2008 5:59 pm

Thanks for the script.
I have a question (x10 question): is the username for your cPanel username?
Example, if my cPanel username was test and the directory was blah and the filename was hello, would I use
php -q /home/test/blah/hello.php ?
User avatar
aopsftw
Registered Member
 
Posts: 15
Joined: Mon Mar 24, 2008 2:17 am

Re: Php script to automatically backup your mysql database

Postby Daniel on Fri Jul 04, 2008 7:26 pm

Yes it is your cpanel username.
-Daniel

Image
User avatar
Daniel
Site Admin
 
Posts: 474
Joined: Wed Dec 05, 2007 4:59 pm
Location: United Kingdom


Return to Website Development

Who is online

Users browsing this forum: No registered users and 0 guests

cron