PHP Classes

How to Backup Wordpress Site Manually Using the Tool Backup4WP: Backup and restore your WordPress website

Recommend this page to a friend!
  Info   View files Example   View files View files (19)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (2)    
Last Updated Ratings Unique User Downloads Download Rankings
2023-11-09 (7 months ago) RSS 2.0 feedNot enough user ratingsTotal: 62 All time: 10,439 This week: 71Up
Version License PHP version Categories
backup4wp 1.2MIT/X Consortium ...7Tools, Security, AJAX, Blogs, PHP 7, A...
Description 

Author

This package can backup and restore your WordPress website.

It provides a Web page that can configure and perform a backup of WordPress files and database.

The package can also restore a WordPress backup if necessary.

Innovation Award
PHP Programming Innovation award winner
November 2023
Winner
WordPress is a prevalent PHP content management system used to serve many sites.

WordPress sites are also targeted by people with bad intentions that may cause harm to a WordPress site installation.

It is always a good idea to take a backup of the files and database of the WordPress site, just in case something terrible happens.

This package provides a standalone tool that can backup and restore the files and database of a WordPress site.

It works independently from the WordPress site itself. So, if a WordPress site stops working due to some damage in the WordPress installation, this tool can still be used to restore the WordPress database and files.

Manuel Lemos
Picture of Olaf Lederer
  Performance   Level  
Name: Olaf Lederer is available for providing paid consulting. Contact Olaf Lederer .
Classes: 11 packages by
Country: The Netherlands The Netherlands
Age: 53
All time rank: 41 in The Netherlands The Netherlands
Week rank: 246 Down6 in The Netherlands The Netherlands Down
Innovation award
Innovation award
Nominee: 2x

Winner: 1x

Instructions

Installation

Using Composer, just run the following code within the public HTML directory from your WordPress website:

composer create-project finalwebsites/backup4wp:dev-master mybackup

Replace the directory name "mybackup" with your unique name, if you like.

Manual installation

Download the the zip file here. Extract and upload the files into a directory named "mybackup" (or some other name) right into the website's public folder. Access the tool and enter your email address and enter your MailerSend API key or your SMTP credentials. Confirm your email address via the link you get in your mailbox.

If you like to use the authorization feature provided by Apache, than continue to "Apache authentication" and enter your details on that page. If you need the "Download" option for your backups, you need to change the variable ENABLE_DOWNLOADS to "true" inside the file libs > func.php.

Example

<?php
include_once 'libs/func.php';
include_once
'libs/html.php';
get_authorized();
//update_mybackup();
$msg = '';
$alert_css = '';
if (isset(
$_GET['msg']) && $_GET['msg'] == 'confirmed') {
   
$alert_css = 'alert alert-success';
   
$msg = 'Your email address is confirmed and valid.';
}

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Manage Backups | Backup4WP</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link href="mbr.css" rel="stylesheet">
  </head>
  <body>
    <?php echo mb_navigation('index'); ?>
<div class="container outwrapper">
      <div class="starter-template">
        <h1>Backup4WP <small>Manage Backups</small></h1>
        <p class="lead">Create backups from your WordPress website and restore files if necessary.</p>
        <form role="form" id="myform">
            <input type="hidden" name="Submitform" value="1">
            <p>Check which directories you like to exclude from the backup. ZIP files and the current directory (for example "mybackup") are always excluded!</p>
            <div class="form-group">
                <label class="checkbox-inline">
                <input type="checkbox" name="exclude[]" value="cache" checked>
                excl. cache
              </label>
              <label class="checkbox-inline">
                <input type="checkbox" name="exclude[]" value="uploads" checked>
                excl. uploads
              </label>
              <label class="checkbox-inline">
                <input type="checkbox" name="exclude[]" value="themes">
                excl. themes
              </label>
              <label class="checkbox-inline">
                <input type="checkbox" name="exclude[]" value="plugins">
                excl. plugins
              </label>
              <label class="checkbox-inline text-muted">
                <input type="checkbox" name="excldb" value="1">
                excl. Database
              </label>
            </div>
            <div class="form-group">
                <label>Backup description</label>
                <input type="text" class="form-control" name="description" placeholder="Optional...">
            </div>
            <div class="text-right">
                <button type="button" class="btn btn-default submitbtn" value="full">Full backup (incl. WP Core)</button>
                <button type="button" class="btn btn-primary submitbtn" value="part">Part. backup (wp-content dir)</button>
            </div>
        </form>

        <div id="msg" class="<?php echo $alert_css; ?>" role="alert"><?php echo $msg; ?></div>
        <h2>Your backups</h2>
        <table class="table table-striped filelist">
            <thead>
                <tr>
                  <th>#</th>
                  <th>Backup</th>
                  <th>Filesize</th>
                  <th>Date &amp; time</th>
                  <th colspan="2">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $i
= 1;

           
$types = array('full' => 'Full backup', 'part' => 'Partial backup');
           
$db = new SQLite3(DATAPATH.'wpbackupsDb.sqlite');
           
$default = '<tr><th>&nbsp;</th><td colspan="6">No backups right now!</td></tr>';
           
$result = $db->query("SELECT * FROM wpbackups WHERE 1 ORDER BY insertdate DESC");

           
$tablehtml = '';
            while (
$res = $result->fetchArray()) {
               
$details = $types[$res['backuptype']];
                if (
$res['database'] == 0) $details .= ' - No database';
               
$details .= ' - Excl. directories: ';
                if (
$excl = unserialize($res['excludedata'])) {
                   
$details .= (count($excl) > 0) ? implode(', ', $excl) : 'none';
                } else {
                   
$details .= 'none';
                }
               
$enable_dlds = (ENABLE_DOWNLOADS) ? '' : ' disabled="disabled"';
               
$tablehtml .= '
                <tr id="'
.$res['id'].'">
                  <th scope="row">'
.$i.'</th>
                  <td>'
.$details.'<br><em>'.$res['description'].'</em></td>
                  <td>'
.filesizeConvert($res['dirsize']).'</td>
                  <td>'
.date('d-m-Y H:i:s', $res['insertdate']).'</td>
                  <td><a href="javascript:void(0);" class="btn btn-default btn-xs download" '
.$enable_dlds.'>Download</a></td>
                  <td><a href="javascript:void(0);" class="btn btn-warning btn-xs restore">Restore</a></td>
                  <td><a href="javascript:void(0);" class="btn btn-danger btn-xs delete">Delete</a></td>
                </tr>'
;
               
$i++;
            }
            echo (
$tablehtml != '') ? $tablehtml : $default;

           
?>
</tbody>
        </table>
      </div>

    </div><!-- /.container -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <script>

    jQuery(document).ready(function($) {

        $('.submitbtn').click(function(e) {
            $('#msg').removeClass('alert alert-success').html('');
            var btn = $(this);
            var btntext = $(this).text();
            var btnval = $(this).val();
            btn.text('Please wait...');
            $.ajax({
                url: "libs/backup.php",
                type: 'POST',
                data: $('form#myform').serialize() + '&typebackup=' + btnval,
                success: function (data) {
                    btn.text(btntext);
                    if (data == 'okay') {
                        $('#msg').addClass('alert alert-success').html('The WordPress backup was succesfully, <a href="index.php">click here</a> to refresh the backup list.');
                        setTimeout(location.reload.bind(location), 5000);
                    } else {
                        $('#msg').addClass('alert alert-danger').html(data);
                    }
                }
            });
            e.preventDefault();
        });

        $('.delete').click(function(e) {
            $('#msg').removeClass('alert alert-success').html('<img src="img/loadingAnimation.gif" alt="Please wait...">');
            var id = $(this).closest('tr').attr('id');
            $.ajax({
                url: "libs/delete.php",
                type: 'POST',
                data: 'delid=' + id,
                success: function (data) {
                    if (data == 'okay') {
                        $('#msg').addClass('alert alert-success').html('The WordPress backup is removed, <a href="index.php">click here</a> to refresh the backup list.');
                        setTimeout(location.reload.bind(location), 5000);
                    } else {
                        //
                    }
                }
            });
            e.preventDefault();
        });

        $('.restore').click(function(e) {
            $('#msg').removeClass('alert alert-danger alert-success').html('<img src="img/loadingAnimation.gif" alt="Please wait...">');
            var id = $(this).closest('tr').attr('id');
            $.ajax({
                url: "libs/restore.php",
                type: 'POST',
                data: 'backupid=' + id,
                success: function (data) {
                    if (data == 'okay') {
                        $('#msg').addClass('alert alert-success').html('The WordPress backup is succesfully restored.');
                        setTimeout(location.reload.bind(location), 5000);
                    } else {
                        $('#msg').addClass('alert alert-danger').html(data);
                    }
                }
            });
            e.preventDefault();
        });
        $('.download').click(function(e) {
            e.preventDefault();
            var id = $(this).closest('tr').attr('id');
            $(this).attr("disabled", true);
            $('#msg').addClass('alert alert-info').html('Please wait until the download is done. <a href="index.php">Click here</a> to refresh the backup list.');
            window.location.href = 'download.php?dlid=' + id;
        });
    });

    </script>
  </body>
</html>


Details

Backup4WP

You know the problem, you've created a backup for your website using a WordPress backup plugin and your WordPress website breaks after an update. Next you can't restore your website to the previous version because you can't access the WP dashboard anymore. Using this backup tool you're able to create a backup outside WordPress. Access the tool again if you need to restore the website. We use the tool to create backups if we install a new theme / plugin or before we do some (smaller) updates.

> Are you looking for the Backup4WP WordPress plugin? The WordPress plugin review team decided to decline our submission. They think that the plugin's concept doesn't follow the rules for a listing in the repository. We accept their decision and removed the plugin here from Github as well.

How does it work?

The backup tool makes a copy from your WordPress website and stores the files in a directory outside the public directory. A database dump is also stored in the same directory. During the restore function the files from the backup are moved back to the original location. The database dump is used to restore the database as well.

Test the tool first!

This tool is using the Linux command line tool "rsync" to copy all the files. We're using the tool for years and it works perfect on all our web servers. It might break your site during the restore, so try the backup tool first on a similar test site.

Security

The tool doesn't store any database logins and all files are stored in a directory which is not accessible via the public website. To access the Backup4WP tool, you need to authorize via a link that is send to your own email address. The session expires 4 hours of activity.

If your web host is based on Apache, the is an option to protect the directory using a login/password or by white-listing your IP address.

Features

  • Super fast, a backup from a 500MB website takes only seconds!
  • Optional: Download your backups and use the ZIP file for the site import in Local (by Flywheel)
  • Quick setup, using email credentials from existing plugins like MailerSend SMTP or WP Mail SMTP
  • Apache user can authenticate via login/password or IP address
  • Backup with a single mouse click (full or partly backups)
  • Exclude themes, plugins or media files
  • Restore your site even if the WordPress website doesn't work anymore
  • Delete old backups with a single click
  • Place notes with every backup

Installation

Using Composer, just run the following code within the public HTML directory from your WordPress website:

composer create-project finalwebsites/backup4wp:dev-master mybackup

Replace the directory name "mybackup" with your unique name, if you like.

Manual installation

Download the the zip file here. Extract and upload the files into a directory named "mybackup" (or some other name) right into the website's public folder. Access the tool and enter your email address and enter your MailerSend API key or your SMTP credentials. Confirm your email address via the link you get in your mailbox.

If you like to use the authorization feature provided by Apache, than continue to "Apache authentication" and enter your details on that page. If you need the "Download" option for your backups, you need to change the variable ENABLE_DOWNLOADS to "true" inside the file libs > func.php.

Installation snippet for ManageWP users

Use this snippet if you use ManageWP. Just run the code and access the tool and finish the "Installation". Continue with the Installation as subscribed before!

<?php
$dir = dirname(dirname(dirname(__DIR__))).'/mybackup';
if (file_exists($dir)) {
	echo 'A "mybackup" directory already exists!';
} else {
    exec('composer -V', $output);
    if (substr($output[0], 0, 8) == 'Composer') {
		exec('composer create-project finalwebsites/backup4wp:dev-master mybackup'); // you can use a different directory name (instead of "mybackup")
        echo 'Downloaded and installed Backup4WP using Composer';
	} else {
		echo 'Composer isn\'t supported by your web host.';
	}
}

Update notes

18th March 2023 In this version we replaced the Sendgrid email option with MailerSend. Sendgrid changed their offer and the free option with 12.000 monthly emails isn't available anymore (for new accounts). In place of the Sendgrid API, you can use the Mailersend API. They offer a free version with 12.000 emails per month and many other options, Sendgrid doesn't offer. If you still prefer Sendgrid, you can still use Backup4WP while using the SMTP email option.

4th November 2022 In some situations there was a PHP memory error while reading the database backup in the restore mode. We fixed it by reading the file line by line using fgets() instead of the file() function.

11th September 2022 We did several updates and bug fixes for the login function and the options page. In the past it doesn't worked well during the setup, if some setting wasn't correct. These should be fixed now. There is also also a log out function available now. We advise to update the application immediately to prevent yourself from future problems. You can keep you current database and files, only the files from the application are modified.

1st May 2022 First release v1.1.0, from today on we're using release tags. Do you like to use Composer? Than is this update for you. We packaged Backup4WP and you're able to install the tool using Composer. The PHPMailer, Sendgrid and Mysqldump library are not included in our distribution anymore. Don't worry for the manual installation, we offer a ZIP file with all the library files included. During the installation, you can choose the directory name. Instead of "mybackup", you can use your own name. This makes it a bit more safe if you choose a random name. From our prospective it's safe to update the application for installations from the last year.

17th April 2022 If your WordPress website is using the Easy SMTP plugin, Backup4WP will recognize these settings too. Plus, if you use an API key from Sendgrid as a password for this SMTP plugin, the API key is also pre-filled inside the "Sendgrid" section. We changed also the order on how the obtained settings are used: 1. Easy SMTP, 2. WP Mail SMTP and 3. the old Sendgrid plugin.

3rd April 2022 If you like to download your backups, it's necessary now to set the constant variable to "true" inside the file "func.php". Most people doesn't need the download feature. This modification is temporary solution until we find a better way to do this on the options page.

19th March 2022 The email sender name is now the domain name. That makes it easier to recognize the email message in your inbox if you use the Backup4WP tool for multiple websites.

30th January 2021 The directory structure for single backup is changed. The site files are stored in a separate directory now. Remove old backups before you update to the latest version of Backup4WP. The restore function will not work with old backups. Beside the new directory structure, we added a new feature: Downloads. Now you can download your entire backup as one ZIP file. The structure of the ZIP file is compatible with the site import function in Local (by Flywheel).

12th December 2020 Some users doesn't like the authorization via the magic link. That's the reason that we've placed the "old" Apache authorization method back to the backup tool. If you enable the Apache authorization option, the email based method isn't used anymore.

14th September 2020 We changed the options page that users can use their SMTP server credentials now. To keep those settings in Backup4WP, we added several columns to the table "backupsettings". To get the update you need to replace the whole "mybackup" directory (keep your "backups" directory!) and visit the main page. The function "update_mybackup()" will add the missing database table columns. Optionally, add your own SMTP server credentials.

Credits


  Files folder image Files  
File Role Description
Files folder imageimg (1 file)
Files folder imagelibs (9 files)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file download.php Example Example script
Accessible without login Plain text file index.php Example Example script
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file login.php Aux. Auxiliary script
Accessible without login Plain text file mbr.css Data Auxiliary data
Accessible without login Plain text file options.php Example Example script
Accessible without login Plain text file README.md Doc. Read me
Accessible without login Plain text file setup-apache-authentication.php Aux. Auxiliary script

  Files folder image Files  /  img  
File Role Description
  Accessible without login Image file loadingAnimation.gif Icon Icon image

  Files folder image Files  /  libs  
File Role Description
  Accessible without login Plain text file backup.php Example Example script
  Accessible without login Plain text file delete.php Example Example script
  Accessible without login Plain text file func.php Example Example script
  Accessible without login Plain text file html.php Aux. Auxiliary script
  Accessible without login Plain text file ip_protect.php Aux. Auxiliary script
  Accessible without login Plain text file password_protect.php Aux. Auxiliary script
  Accessible without login Plain text file restore.php Example Example script
  Accessible without login Plain text file save_options.php Example Example script
  Accessible without login Plain text file send_login.php Example Example script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:62
This week:0
All time:10,439
This week:71Up