MagicWP Docs

Restore Backup

Restore your WordPress site from backup files with step-by-step guidance

Restore Backup

Restore your WordPress site from backup files safely and efficiently. Choose from various restoration methods based on your backup type and requirements.

Preparation Before Restoration

Pre-Restoration Checklist

  • Backup Current Site: Create backup of current site before restoration
  • Verify Backup Integrity: Ensure backup file is not corrupted
  • Check Server Resources: Ensure adequate server resources for restoration
  • Review Backup Contents: Understand what will be restored
  • Plan Downtime: Schedule restoration during low-traffic periods
  • Notify Stakeholders: Inform users about planned restoration
  • Test Environment: Consider testing restoration in staging first

Environment Assessment

function assess_restoration_environment() {
    $assessment = array(
        'php_version' => PHP_VERSION,
        'memory_limit' => ini_get('memory_limit'),
        'max_execution_time' => ini_get('max_execution_time'),
        'upload_max_filesize' => ini_get('upload_max_filesize'),
        'post_max_size' => ini_get('post_max_size'),
        'available_space' => disk_free_space(ABSPATH),
        'mysql_version' => $GLOBALS['wpdb']->db_version(),
        'wordpress_version' => get_bloginfo('version')
    );

    // Check PHP extensions
    $required_extensions = array('mysql', 'mysqli', 'pdo_mysql', 'zip', 'xml');
    $assessment['php_extensions'] = array();
    foreach ($required_extensions as $ext) {
        $assessment['php_extensions'][$ext] = extension_loaded($ext);
    }

    return $assessment;
}

Restoration Methods

Method 1: One-Click Restore

Automated Database Restore

function restore_database_backup($backup_path, $target_database = null) {
    if (!file_exists($backup_path)) {
        return new WP_Error('backup_not_found', 'Database backup file not found.');
    }

    // Use target database or current database
    $database_name = $target_database ?: DB_NAME;

    // Create MySQL connection
    $mysql_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

    if (!$mysql_connection) {
        return new WP_Error('database_connection_failed', 'Failed to connect to database server.');
    }

    // Select target database
    if (!mysqli_select_db($mysql_connection, $database_name)) {
        return new WP_Error('database_selection_failed', 'Failed to select target database.');
    }

    // Read and execute SQL file
    $sql_content = file_get_contents($backup_path);

    if ($sql_content === false) {
        return new WP_Error('backup_read_failed', 'Failed to read backup file.');
    }

    // Split SQL file into individual statements
    $sql_statements = array_filter(array_map('trim', explode(';', $sql_content)));

    $executed_statements = 0;
    $errors = array();

    foreach ($sql_statements as $statement) {
        if (!empty($statement)) {
            $result = mysqli_query($mysql_connection, $statement);

            if ($result === false) {
                $errors[] = mysqli_error($mysql_connection) . ' (Statement: ' . substr($statement, 0, 100) . '...)';
            } else {
                $executed_statements++;
            }
        }
    }

    mysqli_close($mysql_connection);

    return array(
        'success' => empty($errors),
        'executed_statements' => $executed_statements,
        'errors' => $errors
    );
}

Automated File Restore

function restore_file_backup($backup_path, $target_directory = null) {
    $target_dir = $target_directory ?: ABSPATH;

    if (!file_exists($backup_path)) {
        return new WP_Error('backup_not_found', 'File backup not found.');
    }

    // Ensure target directory exists
    if (!is_dir($target_dir)) {
        wp_mkdir_p($target_dir);
    }

    // Get backup file extension
    $file_extension = pathinfo($backup_path, PATHINFO_EXTENSION);

    if ($file_extension === 'zip') {
        // Handle ZIP archives
        $result = restore_zip_backup($backup_path, $target_dir);
    } elseif (in_array($file_extension, array('tar', 'gz'))) {
        // Handle TAR archives
        $result = restore_tar_backup($backup_path, $target_dir);
    } elseif (is_dir($backup_path)) {
        // Handle directory copy
        $result = restore_directory_backup($backup_path, $target_dir);
    } else {
        return new WP_Error('unsupported_backup_format', 'Unsupported backup format.');
    }

    return $result;
}

function restore_zip_backup($zip_path, $target_dir) {
    $zip = new ZipArchive();

    if ($zip->open($zip_path) !== true) {
        return new WP_Error('zip_open_failed', 'Failed to open ZIP archive.');
    }

    // Extract files
    if (!$zip->extractTo($target_dir)) {
        $zip->close();
        return new WP_Error('zip_extract_failed', 'Failed to extract ZIP archive.');
    }

    $zip->close();

    return array(
        'success' => true,
        'extracted_files' => $zip->numFiles,
        'target_directory' => $target_dir
    );
}

function restore_tar_backup($tar_path, $target_dir) {
    $command = "tar -xzf " . escapeshellarg($tar_path) . " -C " . escapeshellarg($target_dir);

    $output = array();
    $return_code = 0;

    exec($command, $output, $return_code);

    if ($return_code !== 0) {
        return new WP_Error('tar_extract_failed', 'Failed to extract TAR archive.');
    }

    return array(
        'success' => true,
        'command_output' => $output,
        'target_directory' => $target_dir
    );
}

Method 2: Selective Restore

Database Table Restore

function restore_specific_database_tables($backup_path, $tables_to_restore) {
    if (!file_exists($backup_path)) {
        return new WP_Error('backup_not_found', 'Database backup file not found.');
    }

    $mysql_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    if (!$mysql_connection) {
        return new WP_Error('database_connection_failed', 'Failed to connect to database.');
    }

    $sql_content = file_get_contents($backup_path);
    $sql_statements = array_filter(array_map('trim', explode(';', $sql_content)));

    $restored_tables = array();
    $errors = array();

    foreach ($sql_statements as $statement) {
        // Check if statement is for a table we want to restore
        foreach ($tables_to_restore as $table) {
            if (strpos($statement, "CREATE TABLE `$table`") !== false ||
                strpos($statement, "INSERT INTO `$table`") !== false) {

                $result = mysqli_query($mysql_connection, $statement);

                if ($result === false) {
                    $errors[] = "Failed to restore table $table: " . mysqli_error($mysql_connection);
                } else {
                    if (!in_array($table, $restored_tables)) {
                        $restored_tables[] = $table;
                    }
                }
                break;
            }
        }
    }

    mysqli_close($mysql_connection);

    return array(
        'success' => empty($errors),
        'restored_tables' => $restored_tables,
        'errors' => $errors
    );
}

File Category Restore

function restore_file_categories($backup_path, $categories_to_restore, $target_dir = null) {
    $target_dir = $target_dir ?: ABSPATH;

    // Define file categories and their patterns
    $file_categories = array(
        'themes' => array('wp-content/themes/*'),
        'plugins' => array('wp-content/plugins/*'),
        'uploads' => array('wp-content/uploads/*'),
        'core' => array('wp-admin/*', 'wp-includes/*', '*.php', '*.css', '*.js'),
        'config' => array('wp-config.php', '.htaccess')
    );

    $extracted_files = array();

    foreach ($categories_to_restore as $category) {
        if (!isset($file_categories[$category])) {
            continue;
        }

        $patterns = $file_categories[$category];

        // Extract files matching the patterns
        $files_in_category = extract_files_by_pattern($backup_path, $patterns, $target_dir);

        $extracted_files[$category] = $files_in_category;
    }

    return array(
        'success' => true,
        'extracted_files' => $extracted_files,
        'target_directory' => $target_dir
    );
}

function extract_files_by_pattern($backup_path, $patterns, $target_dir) {
    $extracted_files = array();

    // For ZIP files
    if (pathinfo($backup_path, PATHINFO_EXTENSION) === 'zip') {
        $zip = new ZipArchive();

        if ($zip->open($backup_path) === true) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $file_name = $zip->getNameIndex($i);

                // Check if file matches any pattern
                foreach ($patterns as $pattern) {
                    if (fnmatch($pattern, $file_name)) {
                        $extracted_path = $target_dir . '/' . $file_name;
                        wp_mkdir_p(dirname($extracted_path));

                        // Extract the file
                        $zip->extractTo($target_dir, $file_name);
                        $extracted_files[] = $file_name;
                        break;
                    }
                }
            }
            $zip->close();
        }
    }

    return $extracted_files;
}

Post-Restoration Tasks

Database Updates

function update_restored_database_urls($old_url, $new_url) {
    global $wpdb;

    $tables_to_update = array(
        'posts' => array('post_content', 'guid'),
        'postmeta' => array('meta_value'),
        'options' => array('option_value'),
        'comments' => array('comment_content'),
        'links' => array('link_url')
    );

    $updated_rows = 0;

    foreach ($tables_to_update as $table => $columns) {
        foreach ($columns as $column) {
            $table_name = $wpdb->prefix . $table;

            // Check if table exists
            if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name) {
                $result = $wpdb->query($wpdb->prepare(
                    "UPDATE $table_name SET $column = REPLACE($column, %s, %s)",
                    $old_url,
                    $new_url
                ));

                if ($result !== false) {
                    $updated_rows += $result;
                }
            }
        }
    }

    return $updated_rows;
}

File Permission Fixes

function fix_restored_file_permissions($directory = null) {
    $directory = $directory ?: ABSPATH;

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
    );

    $fixed_files = 0;
    $fixed_directories = 0;

    foreach ($iterator as $item) {
        if ($item->isFile()) {
            // Set file permissions to 644
            if (chmod($item->getPathname(), 0644)) {
                $fixed_files++;
            }
        } elseif ($item->isDir()) {
            // Set directory permissions to 755
            if (chmod($item->getPathname(), 0755)) {
                $fixed_directories++;
            }
        }
    }

    return array(
        'fixed_files' => $fixed_files,
        'fixed_directories' => $fixed_directories
    );
}

WordPress Reinitialization

function reinitialize_wordpress_after_restore() {
    global $wp_rewrite;

    // Flush rewrite rules
    $wp_rewrite->flush_rules();

    // Clear all caches
    wp_cache_flush();

    // Clear any object caches
    if (function_exists('wp_cache_clear_cache')) {
        wp_cache_clear_cache();
    }

    // Update WordPress options
    update_option('permalink_structure', get_option('permalink_structure'));

    // Clear any transient caches
    global $wpdb;
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_%'");

    // Regenerate theme roots
    if (function_exists('regenerate_theme_roots')) {
        regenerate_theme_roots();
    }

    return true;
}

Restoration Verification

Site Health Check

function perform_restoration_health_check() {
    $health_check = array(
        'database_connection' => false,
        'wordpress_core' => false,
        'active_theme' => false,
        'essential_plugins' => false,
        'file_permissions' => false,
        'site_accessibility' => false
    );

    // Check database connection
    try {
        global $wpdb;
        $wpdb->get_var("SELECT 1");
        $health_check['database_connection'] = true;
    } catch (Exception $e) {
        $health_check['database_errors'] = $e->getMessage();
    }

    // Check WordPress core files
    $core_files = array(
        'wp-admin/index.php',
        'wp-includes/version.php',
        'wp-content/themes/index.php'
    );

    $missing_core_files = array();
    foreach ($core_files as $file) {
        if (!file_exists(ABSPATH . $file)) {
            $missing_core_files[] = $file;
        }
    }

    $health_check['wordpress_core'] = empty($missing_core_files);
    if (!empty($missing_core_files)) {
        $health_check['missing_core_files'] = $missing_core_files;
    }

    // Check active theme
    $active_theme = wp_get_theme();
    $health_check['active_theme'] = $active_theme->exists();

    // Check essential plugins
    $essential_plugins = array('akismet/akismet.php', 'hello.php');
    $inactive_essential = array();

    foreach ($essential_plugins as $plugin) {
        if (!is_plugin_active($plugin) && file_exists(WP_PLUGIN_DIR . '/' . $plugin)) {
            $inactive_essential[] = $plugin;
        }
    }

    $health_check['essential_plugins'] = empty($inactive_essential);

    // Check file permissions
    $writable_dirs = array(
        'wp-content/',
        'wp-content/uploads/',
        'wp-content/themes/',
        'wp-content/plugins/'
    );

    $non_writable_dirs = array();
    foreach ($writable_dirs as $dir) {
        if (!wp_is_writable(ABSPATH . $dir)) {
            $non_writable_dirs[] = $dir;
        }
    }

    $health_check['file_permissions'] = empty($non_writable_dirs);

    // Check site accessibility
    $response = wp_remote_get(home_url());
    $health_check['site_accessibility'] = !is_wp_error($response) &&
                                         wp_remote_retrieve_response_code($response) === 200;

    return $health_check;
}

Content Verification

function verify_restored_content() {
    $verification = array(
        'total_posts' => 0,
        'published_posts' => 0,
        'total_pages' => 0,
        'total_users' => 0,
        'active_plugins' => 0,
        'themes_available' => 0,
        'media_files' => 0
    );

    // Count posts and pages
    $verification['total_posts'] = wp_count_posts('post')->publish;
    $verification['published_posts'] = wp_count_posts('post')->publish;
    $verification['total_pages'] = wp_count_posts('page')->publish;

    // Count users
    $verification['total_users'] = count_users()['total_users'];

    // Count active plugins
    $verification['active_plugins'] = count(get_option('active_plugins', array()));

    // Count available themes
    $themes = wp_get_themes();
    $verification['themes_available'] = count($themes);

    // Count media files
    $media_query = new WP_Query(array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'inherit'
    ));
    $verification['media_files'] = $media_query->found_posts;

    return $verification;
}

Rollback Procedures

Automatic Rollback

function create_restoration_rollback_point() {
    $rollback_point = array(
        'timestamp' => time(),
        'wordpress_version' => get_bloginfo('version'),
        'active_theme' => get_option('stylesheet'),
        'active_plugins' => get_option('active_plugins'),
        'database_backup' => create_rollback_database_backup(),
        'file_backup' => create_rollback_file_backup()
    );

    update_option('restoration_rollback_point', $rollback_point);

    return $rollback_point;
}

function execute_restoration_rollback() {
    $rollback_point = get_option('restoration_rollback_point');

    if (!$rollback_point) {
        return new WP_Error('no_rollback_point', 'No rollback point available.');
    }

    // Restore database
    if (isset($rollback_point['database_backup'])) {
        restore_database_backup($rollback_point['database_backup']);
    }

    // Restore files
    if (isset($rollback_point['file_backup'])) {
        restore_file_backup($rollback_point['file_backup']);
    }

    // Reactivate original theme and plugins
    switch_theme($rollback_point['active_theme']);
    update_option('active_plugins', $rollback_point['active_plugins']);

    // Clear rollback point
    delete_option('restoration_rollback_point');

    return true;
}

Monitoring and Logging

Restoration Activity Logging

function log_restoration_activity($action, $details = array()) {
    $log_entry = array(
        'timestamp' => current_time('mysql'),
        'action' => $action,
        'user_id' => get_current_user_id(),
        'ip_address' => $_SERVER['REMOTE_ADDR'],
        'user_agent' => $_SERVER['HTTP_USER_AGENT'],
        'details' => wp_json_encode($details)
    );

    // Store in custom table or log file
    global $wpdb;

    $table_name = $wpdb->prefix . 'restoration_logs';

    // Create table if it doesn't exist
    if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
        create_restoration_logs_table();
    }

    $wpdb->insert($table_name, $log_entry);
}

function create_restoration_logs_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'restoration_logs';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        timestamp datetime DEFAULT CURRENT_TIMESTAMP,
        action varchar(100) NOT NULL,
        user_id bigint(20) unsigned NOT NULL,
        ip_address varchar(45) NOT NULL,
        user_agent text,
        details longtext,
        PRIMARY KEY (id),
        KEY timestamp (timestamp),
        KEY action (action),
        KEY user_id (user_id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

Best Practices

Restoration Best Practices

  1. Test in Staging: Always test restoration in staging environment first
  2. Backup Current State: Create backup before starting restoration
  3. Verify Backup Integrity: Ensure backup is not corrupted
  4. Schedule Wisely: Perform restoration during low-traffic periods
  5. Monitor Progress: Track restoration progress and errors
  6. Test Thoroughly: Verify all functionality after restoration
  7. Have Rollback Plan: Prepare rollback procedures

Safety Measures

  1. Incremental Restoration: Restore in phases to minimize risk
  2. Version Compatibility: Ensure backup compatibility with current environment
  3. Resource Monitoring: Monitor server resources during restoration
  4. Error Handling: Handle restoration errors gracefully
  5. Progress Backup: Create backup points during restoration process

Post-Restoration Tasks

  1. Security Audit: Check for security vulnerabilities
  2. Performance Testing: Verify site performance
  3. Content Verification: Ensure all content is properly restored
  4. URL Updates: Update any hardcoded URLs
  5. Plugin Updates: Update plugins to latest versions

Comprehensive backup restoration with safety and verification measures.

On this page